Okay, so we have around 30 input boxes in our page, and instead of writing a no data line for each one, we have a simple statement:
if( $(div).find('input:text[value=""]').length > 0 ||
$('#checkbox1Wrap').find('input:checkbox:not(:checked)').length > 0 ||
$('#checkbox2Wrap').find('input:checkbox:not(:checked)').length > 0 ||
$(div).find('select option:first-child:selected').length > 0 ||
$(div).find('textarea').val() == ""
){
$(div).prepend('<p class="field_help"> Please complete all fields before moving to next step</p>');
return false;
}
This checks all input fields to check if their length is more than 0, but we want to exclude certain fields from being checked.
For example:
<input type="text" autocomplete="off" value="" name="ext" id="ext">
We don’t want the above input field to be checked.
How can we make it so the if statement skips certain defined IDs?
You can use the
.not()method:Docs here: http://api.jquery.com/not/
I should note that one standard way of doing this is a bit simpler, however, if you don’t mind mixing the business logic of the form with your HTML markup:
In HTML, add a
requiredCSS class to all required elements.In jQuery, specify that class in your selector:
Now only required elements are validated. There are a couple of advantages to this approach:
You could do the same thing in the opposite direction using an
optionalclass too, but I thinkrequiredis a bit better semantically.