Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails check_box_tag set checked with default value

I currently have a rails check_box_tag call that looks like

check_box_tag #{name}

I want to include a checked attribute, which I know I can do with

check_box_tag name, value, checked

But what if I want to set it to checked without explicitly specifying value (I just want to use the default). Or similarly, what if I wanted to specify html options without specifying the checked attribute. Is there a way to do this?

like image 556
Jeff Storey Avatar asked Aug 03 '12 13:08

Jeff Storey


4 Answers

Just wanted to update this. The third parameter for check_box_tag is a boolean value representing the checked status.

check_box_tag name, value, true
like image 147
KPheasey Avatar answered Nov 10 '22 19:11

KPheasey


If you want the checkbox to be checked, then

check_box_tag name, value, {:checked => "checked"} 

otherwise

check_box_tag name, value
like image 30
user2516008 Avatar answered Nov 10 '22 20:11

user2516008


check_box_tag(name, value = "1", checked = false, options = {})

Examples:

check_box_tag 'receive_email', 'yes', true
# => <input checked="checked" id="receive_email" name="receive_email" type="checkbox" value="yes" />

check_box_tag 'tos', 'yes', false, class: 'accept_tos'
# => <input class="accept_tos" id="tos" name="tos" type="checkbox" value="yes" />

check_box_tag 'eula', 'accepted', false, disabled: true
# => <input disabled="disabled" id="eula" name="eula" type="checkbox" value="accepted" />

api.rubyonrails.org

like image 8
shilovk Avatar answered Nov 10 '22 19:11

shilovk


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
like image 4
dimuch Avatar answered Nov 10 '22 21:11

dimuch