Reputation: 11746
I have a large form built with twitter's bootstrap kit. The fields look like so:
<div class="clearfix">
<label for="state_id">State</label>
<div class="input">
<select id="state_id" name="state">
<option value="122">Alabama</option><option value="123">Alaska</option><option value="124">Arizona</option>
</select>
</div>
</div><!-- /clearfix -->
<div class="clearfix">
<label for="city_id">City</label>
<div class="input">
<input type="text" id="city_id" name="city" value="" />
</div>
</div><!-- /clearfix -->
They offer an error class that highlights the field in red like so:
<div class="clearfix error">
<label for="state_id">State</label>
<div class="input">
<select id="state_id" name="state">
<option value="122">Alabama</option><option value="123">Alaska</option><option value="124">Arizona</option>
</select>
</div>
</div><!-- /clearfix -->
Is there a way to use jquery and validate my form fields and add this class if needed?
My jquery call is simply:
$('#form_submit').click(function(){
var formValid = true;
$("div.clearfix").each(function() {
//
});
});
Upvotes: 0
Views: 167
Reputation: 2143
You can validate your forms with above plugin or any other way and then if you find the validation error then use
$("#city_id_input_div").addClass("error");
Where you have to give the id to the each div to which you need to apply the 'error' class.
For example
<div class="clearfix" is="city_id_input_div">
<label for="city_id">City</label>
<div class="input">
<input type="text" id="city_id" name="city" value="" class="large" onclick="removeErrorClass('city_id_input_div');" onkeypress="removeErrorClass('city_id_input_div');"/>
</div>
function removeErrorClass(id)
{
$("#"+id).removeClass("error");
}
this is my way to use 'error' class of the Bootstrap dynamically and remove that class dynamically.
Upvotes: 0
Reputation: 643
Maybe you can consider use the jquery validation plugin just to make the validation rules. Really is a powerful plugin.
example:
$("input [type='text']").rules("add", { minlength: 2 });
So, when you calls $("form").validate()
this function returns all invalid fields.
Upvotes: 2