Reputation: 3098
I would like to validate every single item in my form so in case one is empty I would like to print an alert.
So for that I'm using the form.serializeArray()
to check for any input box that could be empty. but my code is not working. Am I doing it good?
Here's my jsfiddle code
Upvotes: 2
Views: 66
Reputation: 662
You are calling page.find()
instead of $('')
for selecting your form.
To improve your code and don't repeat code uselessly you can change your code like that :
$("#myform").submit(function() {
var formItems = $(this).serializeArray();
formItems.forEach(function (i, v) {
if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
window.alert("need to fill up all those fields");
}
});
});
To not make too many pop-up; you can specify the field who is empty.
$("#myform").submit(function() {
var formItems = $(this).serializeArray();
formItems.forEach(function (i, v) {
if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
$('input[name="' + v.name + '"]').val("This field must not be empty");
}
});
});
Upvotes: 1
Reputation: 931
The .find()
method searches for a specified text in the document and highlights the matches.
You can further simplify your code:
$( "#myform" ).submit(function( form ) {
$(this).serializeArray().forEach(function (i, v) {
if (v.value == '' || v.value == null || typeof v.value == 'undefined') {
alert("need to fill up all those fields");
}
});
});
Upvotes: 1
Reputation: 13211
instead of var form = page.find(..);
use var form = $(..);
modified.. http://jsfiddle.net/vqr22ebz/6/
But there is another problem, you are calling the alert for every empty field.
Upvotes: 1