Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio buttons on form not rendering correctly after form validation failure- bootstrap

Rails 4 app with Bootstrap 3

I have a form that includes inputs from radio buttons:

<strong> Radio button options on form </strong><br>
   <div class="form-group">
     &nbsp<%= f.radio_button :category, 'A' %> &nbsp <%= f.label "A", "A" %><br /> 
     &nbsp<%= f.radio_button :category, 'B' %> &nbsp <%= f.label "B", "B" %><br />  
     &nbsp<%= f.radio_button :category, 'C' %> &nbsp <%= f.label "C", "C" %><br />
   </div>

The first time the form is loaded, everything looks correct:

enter image description here

My issue is that if the form fails due to a validation error (missing required input, etc, anywhere on the form), when the page re-renders, the radio button and the label are displaying on two different lines:

enter image description here

How do I fix this issue?

Updated The generated HTML for each is: Original (correct):

    <strong> Radio button options on form </strong><br>
    <div class="form-group">
      &nbsp<input id="listing_category_1" name="listing[category]" type="radio" value="1" /> &nbsp <label for="listing_1">A</label><br /> 
      &nbsp<input id="listing_category_2" name="listing[category]" type="radio" value="2" /> &nbsp <label for="listing_2">B</label><br />  
      &nbsp<input id="listing_category_3" name="listing[category]" type="radio" value="3" /> &nbsp <label for="listing_3">C</label><br />
    </div>

And for the re-rendering (incorrect):

    <strong> Radio button options on form </strong><br>
    <div class="form-group">
      &nbsp<div class="field_with_errors"><input id="listing_category_1" name="listing[category]" type="radio" value="1" /></div> &nbsp <label for="listing_1">A</label><br /> 
      &nbsp<div class="field_with_errors"><input id="listing_category_2" name="listing[category]" type="radio" value="2" /></div> &nbsp <label for="listing_2">B</label><br />  
      &nbsp<div class="field_with_errors"><input id="listing_category_3" name="listing[category]" type="radio" value="3" /></div> &nbsp <label for="listing_3">C</label><br />
    </div>
like image 284
dmt2989 Avatar asked Jan 12 '23 01:01

dmt2989


1 Answers

This is because Rails wrap fields with errors into a div:

<div class="field_with_errors">
  <input name="foo" type="radio" value="1" />
</div>

One way to solve could be customize this css class, for example making div display property inline instead of block:

.field_with_errors { display: inline; }

Another option, modify Rails setting to change default behaviour when displaying errors:

config.action_view.field_error_proc = Proc.new { |html_tag, instance| "<span class='field_with_errors'>#{html_tag}</span>".html_safe }
like image 124
markets Avatar answered Jan 19 '23 10:01

markets