How can I make a check box default to being "checked" when it is initially displayed?
I've not found a "Rails" way to do this (that works) so I did it with JavaScript. Is there a proper way to do this in Rails? I'm using Rails 1.2.3.
check_box inside a form builder, plus you have to add a label to display it. The construct you are using just generate the <input type="checkbox" value="something" /> and not the label, that you have to add, just like text or with a <%= label_tag 'whatever' %> .
Rails 3.x
= form_for(@user) do |f| = f.check_box :subscribe, {checked: true, ...}
This sets the checked state to true and should work fine. Note the ruby 1.9.x syntax of the hash, for ruby 1.8.x use hash tag format {:checked => true, ...}
If you're using check_box
in the context of a form, then the check box will show whatever value that field has.
@user = Person.find(:first) @user.active = true check_box 'user', 'active' #=> will be checked by default
If you're using check_box_tag
, the third parameter is the initial state (check_box_tag
doc):
check_box_tag "active", 1, true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With