Sagar Singh Sagar Singh - 6 months ago 12
Javascript Question

How to check for all empty input in form

I have some form which are dynamically generated & have different id, so i thought there could be something that will validate each input, here i what i did

$.fn.isBlank = function() {
var fields = $("#exp0").serialize()
alert('something');
for (var i = 0; i < fields.length; i++) {
if (fields[i].value != '') {
alert('testing');
return false;
}
}
alert('testing2');
return true;
};


But above script doesn't work i don't know why, even the alerts are not triggered

here is the full jquery

$(document).on("submit", "#exp0", function(e){
e.preventDefault();
var postData = $("#exp0").serialize()
$.fn.isBlank = function() {
var fields = $("#exp0").serialize()
alert('something');
for (var i = 0; i < fields.length; i++) {
if (fields[i].value != '') {
alert('testing');
return false;
}
}
alert('testing2');
return true;
};
$.ajax({
type: "POST",
url: "/ajax/saveexp",
data: postData,
async: false,
contentType: false,
processData: false,
cache: false,
success: function(msg)
{
bootbox.alert('Your Profile has been updated');
}

});
});

Answer

The main problem seems to be, that you first serialize the form fields (which results in a string) and then try to iterate over the fields in this string (which will not work).

Iterate over the form fields directly instead. With jQuery, you can do that easily:

$("#exp0").find("input").each(function () {
    if ($(this).val() === '') { ... }
});

Another note: defining a function isBlank is not enough, it must be called somewhere. You could remove the declaration and do the check directly in place.

Full code: https://jsfiddle.net/vq3y6bok/1/

Comments