Reputation: 18178
I know this is a simple question, but can you all help me with the following code? I made this function to check that the required fields are filled out in a form. If it finds one of the inputs is blank, then it should stop and return false. If all the elements have content, it should return true. The following function does not work because my return false;
line is inside the jQuery .each
function. It is not returning the new function I defined. How can I handle this?
function check_form(){
$('form .required').each(function(){
if ($(this).val() == ""){
show_dialog('Please enter a value for ' + $(this).attr('name'));
return false;
}
});
return true;
}
This function is returning true every time even if some required fields are blank.
the problem is described in this fiddle: http://jsfiddle.net/f59t4/2/
It works now, thanks everyone!
Upvotes: 1
Views: 2802
Reputation: 342635
Assuming:
1) You want a validation summary of all the problems, and
2) You don't want a field containing all spaces to be counted as valid, then:
function checkform () {
var errors = "";
var $blankFields = $('form .required').filter(function () {
return $.trim($(this).val()) === "";
});
if ($blankFields.length) {
$blankFields.each(function () {
errors += "Please enter a value for " + $(this).attr('name') + "<br />";
});
show_dialog(errors);
return false;
}
return true;
}
Upvotes: 1
Reputation: 12705
try this
function check_form(){
var flag = true;
$('form .required').each(function(){
if ($(this).val() == ""){
show_dialog('Please enter a value for ' + $(this).attr('name'));
flag = false;
}
});
return flag;
}
Upvotes: 4