I saw many places similar question but couldn't fix it.
Here's my function:
function validate_form(){
$('#form_data input[type="text"]').each(function(){
value = $(this).val().trim();
if(value != '' && value != null && value != 0 ){
return true;
}
});
return false;
}
Its not exiting on return true;
. I have also tried e.preventDefault()
but no use.
I saw many places similar question but couldn't fix it.
Here's my function:
function validate_form(){
$('#form_data input[type="text"]').each(function(){
value = $(this).val().trim();
if(value != '' && value != null && value != 0 ){
return true;
}
});
return false;
}
Its not exiting on return true;
. I have also tried e.preventDefault()
but no use.
-
It should be
return false
. – JJJ Commented Apr 1, 2013 at 7:56 - @DipeshParmar using break gives me error – Sachin Prasad Commented Apr 1, 2013 at 7:57
- possible duplicate of How to break/exit from a each() function in JQuery? – JJJ Commented Apr 1, 2013 at 7:57
-
@DipeshParmar It's the jQuery's
.each()
method. It's not a built-in loop structure sobreak
won't work. – JJJ Commented Apr 1, 2013 at 7:58 - 1 Exactly what should the function do? Is the form considered valid if there's at least one field filled in? Or must all fields be filled in? – Ja͢ck Commented Apr 1, 2013 at 8:05
3 Answers
Reset to default 3return
will return from the function it is in. In your code, that is the anonymous function you pass to each
. See the documentation for each:
You can stop the loop from within the callback function by returning
false
.
You are returning true
, not false
so you aren't stopping the loop. Change true
to false
on line 5 of the function.
function validate_form(){
$texts=$('#form_data input[type="text"]'); //cache the object
var len = $texts.length;
var validItems=0;
$texts.each(function(){
value = $(this).val().trim();
if(value === ''){ // value of a text input cannot be null
// or zero unless you've changed in with JS
return false;
}
validItems++;
});
return len===validItems;
}
The function doesn't exactly show what item is invalid, just returns false if any of the items is invalid.
You have to let the .each()
finish before you return from the main function body. You can keep a counter of valid entries you have e across and let the return value depend on that:
function validate_form()
{
var items = $('#form_data input[type="text"]'),
count = items.length,
valid = 0;
items.each(function() {
value = $(this).val().trim();
if (value != '' && value != null && value != 0 ) {
++valid;
}
});
return valid !== count;
}
Btw, I've changed the return value to false
if there's at least one invalid entry; assuming you're using this as onsubmit="return validate_form()"
.