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.
return 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 come 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()".
Related
I want to return false and return from function if I find first blank textbox
function validate(){
$('input[type=text]').each(function(){
if($(this).val() == "")
return false;
});
}
and above code is not working for me :(
can anybody help?
You are jumping out, but from the inner loop, I would instead use a selector for your specific "no value" check, like this:
function validate(){
if($('input[type=text][value=""]').length) return false;
}
Or, set the result as you go inside the loop, and return that result from the outer loop:
function validate() {
var valid = true;
$('input[type=text]').each(function(){
if($(this).val() == "") //or a more complex check here
return valid = false;
});
return valid;
}
You can do it like this:
function validate(){
var rv = true;
$('input[type=text]').each(function(){
if($(this).val() == "") {
rv = false; // Set flag
return false; // Stop iterating
}
});
return rv;
}
That assumes you want to return true if you don't find it.
You may find that this is one of those sitautions where you don't want to use each at all:
function validate(){
var inputs = $('input[type=text]');
var index;
while (index = inputs.length - 1; index >= 0; --index) {
if (inputs[index].value == "") { // Or $(inputs[index]).val() == "" if you prefer
return false;
}
}
// (Presumably return something here, though you weren't in your example)
}
I want to add something to existing answers to clear the behavior of $(selector).each and why it doesn't respect return false in OP's code.
return keyword inside $(selector).each is used to break or continue the loop. If you use return false, it is equivalent to a break statement inside a for/while loop. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration. Source
Because you're returning false, the loop breaks and the function ends up returning undefined in your case.
Your option is to use a var outside $.each or avoid using it altogether as #TJCrowder wrote.
I am trying to make my text boxes red when the value is null. Unfortunately when I submit the form only the text box emp_id turns red and the emp_fn remains the same. I think this is because of the return false function. What do you think. Btw Im a newbie
function emp_add_validate() {
var emp_id = document.emp_add.emp_id.value;
var emp_fn = document.emp_add.emp_fn.value;
if (emp_id == null || emp_id == ""){
document.getElementById("emp_id").classList.add("is-invalid");
return false;
}
if (emp_fn == null || emp_fn == ""){
document.getElementById("emp_fn").classList.add("is-invalid");
return false;
}
}
Perhaps you meant to return false if either if-test fails, but only after you have performed both tests:
function emp_add_validate() {
var emp_id = document.emp_add.emp_id.value;
var emp_fn = document.emp_add.emp_fn.value;
var ok = true;
if (emp_id == null || emp_id == "") {
document.getElementById("emp_id").classList.add("is-invalid");
ok = false;
}
if (emp_fn == null || emp_fn == "") {
document.getElementById("emp_fn").classList.add("is-invalid");
ok = false;
}
return ok;
}
Yes it is because of the return keyword.
The return statement ends function execution and specifies a value to be returned to the function caller.
from mdn web docs
What happen is when the first if block is executed it saw the return keyword and exits the function which makes the second if to not get executed.
You can refractor your code by having the return false statement outside of the if block.
function emp_add_validate() {
var emp_id = document.emp_add.emp_id.value;
var emp_fn = document.emp_add.emp_fn.value;
if (emp_id == null || emp_id == ""){
document.getElementById("emp_id").classList.add("is-invalid");
}
if (emp_fn == null || emp_fn == ""){
document.getElementById("emp_fn").classList.add("is-invalid");
}
return false;
}
I want to check object's each property value if all value equal to 0 then alert. Below code is performing alert if only one property contains 0
var arr={a:"0", b:"1", c:"2"};
$.each(arr,function(i,val){
if(val=="0")
alert(0)
})
You're actually using an Object, not an Array, so loop with for..in
function allEqualTo(obj, test) {
var key;
for (key in obj)
if (obj[key] !== test)
return false;
return true;
}
Now
var o = {a:"0", b:"1", c:"2"};
if (allEqualTo(o, "0"))
alert(0);
else
alert('foobar');
// foobar alerted
If you want it by jquery use this code:
var bOk = true;
$.each(arr,function(i,val){
if (val != 0) return bOk = false;
})
if (bOk) alert(0);
I have a function expression like this :
var inputChecker = function(field) {
return function() {
if(field === '' || field === 'undefined' || field === null) {
return false;
}
return true;
}
}
that I want to use in several different function expressions :
(function($) {
if(inputChecker(x)) {}
})(jQuery);
(function($) {
})(jQuery);
But the problem is inputChecker is not visible in these function expressions when it's declared out of their bodies ? I don't understand why? Isn't inputChecker supposed to be global ?
Dystroy's answer is definitely simpler. But if you want it your way...
The return value of the inputChecker is a function, not boolean. If you want to call the returned function, use () expression:
var fn = inputChecker(x); // gets the function
fn(); // calls the returned function
or shorter
inputChecker(x)();
In your code
(function($) {
if(inputChecker(x)()) {
// custom code here if x is defined
}
})(jQuery);
Note: if you want to check if variable is not undefined, strip the apostrophes - undefined is constant, not string
if(field===undefined)
What you wrote is a function factory. It doesn't return a boolean but a function able to check a property.
This kind of functions is sometimes useful but :
you're here, in the returned function, checking the value of the property received by the factory. As this value can't change (it's embedded in the closure), the produced function holds no more information than just true or false. So it's useless.
you're calling inputChecker(x) as if it was a boolean instead of a function.
So what you probably want is simply
var checkInput = function(field) {
if(field === '' || field === 'undefined' || field === null){
return false;
}
return true;
}
But if you really want to generate different checking functions, dependent on another value, you could use the function factory pattern like this:
var x = true;
var checkInput = (function (x) {
if (x === true) {
return function(field) {
if(field === '' || field === 'undefined' || field === null){
return false;
}
return true;
}
} else {
return function(field) {
//evaluate field differently
}
}
}(x));
Now, dependig on what x is, one or another function will be assigned to checkInput.
I have a jQuery-powered JavaScript function which iterates over a list of fields and checks to see whether they are empty; if so, blocks the submission of the form.
required_fields.forEach(function(field) {
if (field.val() == '')
{
field.addClass('field-highlight');
return false;
}
else
{
field.removeClass('field-highlight');
}
});
// I want to return to here from the return false point
How can I structure this differently to do what I want?
Just use a variable to keep track of the validation:
var is_valid = true;
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
is_valid = false;
return false;
} else {
field.removeClass('field-highlight');
}
});
return is_valid;
Or, you can just use the field-highlight class as well:
required_fields.forEach(function(field) {
if (field.val() == '') {
field.addClass('field-highlight');
return false;
} else {
field.removeClass('field-highlight');
}
});
return $('.field-highlight').length == 0;
use a boolean in the forEach closure, which would be set to true, if the field value is empty. Check that value before submission of form
It sounds like you want to do the following
Update the elements with the field-highlight class based on whether or not they have a value
Block the form submission if any are empty
If so then try the following
var anyEmpty = false;
required_fields.forEach(function() {
if ($(this).value() == '') {
$(this).addClass('field-highlight');
anyEmpty = true;
} else {
$(this).removeClass('field-highlight');
}
});
if (anyEmpty) {
// Block the form
}
Did you write the "forEach" function? If so, that could check the return value of the anon function, and if it is ever false, stop iterating.
If your required_fields is a jQuery object, you could just do this:
var stop = required_fields.removeClass('field-highlight')
.filter("[value == '']").addClass('field-highlight')
.length;
return !!stop
Or perhaps more efficient like this?
var stop = required_fields.filter('.field-highlight').removeClass('field-highlight')
.end().filter("[value == '']").addClass('field-highlight')
.length;
return !!stop