I have the following code for an input text field:
<%= f.label :first_name %>
<%= f.text_field :first_name, class: 'required' %>
which produces the following HTML:
<label for="user_first_name">First name</label>
<input class="required" id="user_first_name" name="user[first_name]" size="30" type="text" />
I noticed that if I validate the fields with Rails the HTML changes to this:
<div class="field_with_errors"><label for="user_first_name">First name</label></div>
<div class="field_with_errors"><input class="required" id="user_first_name" name="user[first_name]" size="30" type="text" value="" /></div>
But I want to validate first on the client side with jQuery. So I provide the following code:
$(document).ready(function(){
$('#new_user').submit(function(event){
$('.required').each(function(){
if(!$.trim($(this).val()))
{
$(this).before('<div class="field_with_errors">');
$(this).after('</div>');
event.preventDefault();
}
});
});
});
But that produces this code:
<div class="field_with_errors"></div>
<input class="required" id="user_first_name" name="user[first_name]" size="30" type="text" value="" />
The div closes in the wrong place…any ideas?
mike
Use
wrap()to warp the elementshttp://api.jquery.com/wrap/
before()andafter()add elements either before or after the target elements and it won’t wrap the elements as you expect. Change,to