Reputation: 2850
From what I can tell, my question should be pretty easy to answer for someone who encountered this issue before ...
I have a signup form in rails which should highlight the fields that are not properly completed when the submit button is clicked (it should also show relevant error messages). The form contains only input fields and a checkbox. While the errors are properly displayed for each part of the form, the checkbox label is not properly highlighted in red when the user tries to submit the form whithout checking the checkbox.
What should I modify in my code to have the checkbox label highlighted when the checkbox is left unchecked?
This is the view code:
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :email %>
<%= f.text_field :email %>
<%= f.label :password %>
<%= f.password_field :password %>
<%= f.label :password_confirmation, "Password confirmation" %>
<%= f.password_field :password_confirmation %>
<br>
<%= f.check_box :terms_of_service %>
<label_for="user_terms_of_service">I agree to the <%= link_to "Terms of Service", policies_path %>
</label>
<br><br>
<%= f.submit "Create my account", :class => "btn btn-large btn-primary" %>
<% end %>
Also, this is what I can see with Firebug for the checkbox after the form is improperly submitted - the problem is that the div with class="field_with_errors" is put before the checkbox label.
<br>
<input type="hidden" value="0" name="user[terms_of_service]">
<div class="field_with_errors">
<input id="user_terms_of_service" type="checkbox" value="1" name="user[terms_of_service]">
</div>
<label_for="user_terms_of_service">
Thank you for your help, Alexandra
Upvotes: 1
Views: 2599
Reputation: 46960
The label syntax is not correct. Try
<%= f.label :user_terms_of_service, "I agree to the #{link_to 'Terms of Service', policies_path}.".html_safe %>
Upvotes: 1
Reputation: 96484
My approach with forms is to try and use the rails standards where possible, e.g.
Add to your User model:
validates_acceptance_of :terms
attr_accessible :terms
In your view,
<%= form_for @user do |f| %>
...
<%= f.check_box :terms %>
...
<% end %>
You actually don't need an extra column in the users table unless you want to grant access to users who have not accepted the terms of service, which... don't exist as they can't complete registrations in the first place.
Upvotes: 2