Reputation: 17757
I have a form with 15 fields(including input types,select box,text area).
I can write a function to validate this form by the ordinary way,but thats not smart coding.I need to use each in this case.
This is what I was thinking:
$("#id1, #id2, #id3... #id15").each(function(){
if ($(this).val == "") {
$(this).closest("#error").css("display", "block");
}
})
Should this validation be class based or id based,am I going the right way?Am i using each() in the right context?
Upvotes: 1
Views: 92
Reputation: 73906
You can use :input
selector here to select all the input elements inside the form like:
$("#formID :input").each(function () {
if ($(this).val() == "") {
$(this).closest("#error").css("display", "block");
}
});
Or maybe add a specific class to all the inputs that you want to validate like validate
and do like:
$(".validate").each(function () {
if ($(this).val() == "") {
$(this).closest("#error").css("display", "block");
}
});
Documentation: http://api.jquery.com/input-selector/
Description: Selects all input, textarea, select and button elements.
Upvotes: 7
Reputation: 1064
Or any tag with id attribute inside the form
$('form *[id]')
or name attr would even better
$('form *[name]')
Upvotes: 2
Reputation: 963
If you have multiple inputs, selects and form elements, add a class like "input-group" to each element and then iterate over that group.
$("form .input-group").each(function(){
if ($(this).val == "") {
$(this).closest("#error").css("display", "block");
}
})
Upvotes: -1