Category: HTML

Rails check_box_tag set checked with condition value

There are no ways to do it directly. But the check_box_tag implementation is trivial, you can monkey patch it or create own helper.

Original implementation:

  def check_box_tag(name, value = "1", checked = false, options = {})
    html_options = { "type" => "checkbox", "name" => name, "id" => sanitize_to_id(name), "value" => value }.update(options.stringify_keys)
    html_options["checked"] = "checked" if checked
    tag :input, html_options
  end

Which can be used in our view as following:

label
  - is_broker_selected = params[:search].present? && params[:search][:type].to_s.include?('Broker')
  div[class="icon-checkbox #{is_broker_selected == true ? 'grey' : ''}"]
  i.fa.fa-user
  = check_box_tag('search[type][]', 'Broker', is_broker_selected, class: 'search_type')
  | Broker

 

Reference: http://stackoverflow.com/questions/11796629/rails-check-box-tag-set-checked-with-default-value#_=_

 

Advertisements