Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkbox not staying checked in rails form

I have this in part of my form_tag

%input{ :type => "checkbox", :name => "form", :value => "#{@t.form}"}

It saves to the database as 1 when i check it the first time, but then if i navigate back to the form it doesn't show up checked..

like image 486
user1738017 Avatar asked Jan 01 '26 17:01

user1738017


1 Answers

Firstly, this is not a recommended way to add the form and fields in rails. But, still to answer you question, you can go with this:

%input{ :type => "checkbox", :name => "form", :value => true, :checked => @t.form ? "checked" : ""}

Notice that I have changed the value part to true as it is the value attribute of the checkbox that will always have the same value.

Now there would be another problem, if the checkbox was previously checked and now you are unchecking it and saving the form then it will not save the value "0" of false in database.

According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value.

Now to avoid this problem, you need to add a hidden field as well.

%input{ :type => "hidden", :name => "form", :value => false}
%input{ :type => "checkbox", :name => "form", :value => true, :checked => @t.form ? "checked" : ""}

Now, If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence.

Note: I will recommend you to use rails methods for generating hidden fields and checkbox.

Update(with form_tag helpers)

= hidden_field_tag('form', '0')
= check_box_tag("form", '1', @t.form)

I think you are using HAML and the form is a boolean field in database.

like image 52
Manoj Monga Avatar answered Jan 03 '26 14:01

Manoj Monga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!