Reputation: 268
im trying to find a way to alert when there is a null values in an object, if its present it should alert fail and if it doesn't it continues with the another action. Currently im able to alert for each key. with this code:
var ave = {
'a': '02',
'b': '04',
'c': '',
'd': '',
'f': '07'
};
var total = 0
$.each(ave, function(key, value) {
var numbersA = total + value.length;
if (numbersA === 0) {
alert("Fail!");
} else {
alert("Pass!");
}
});
It pops up Fail! twice and Pass 3 times. i want it to alert fail even if there is single null value present in the object. Is there way to do it?
Upvotes: 0
Views: 238
Reputation: 146191
I missed it but the shortest one
var ave = {
'a': '1',
'b': '04',
'c': '4',
'd': '',
'f': '1'
};
(function(){
var v='Success';
for(var x in ave) if(!ave[x]) { v='Fail'; break;}
alert(v);
})();
OR
function is_falsy(arg){
var what=true;
for(var x in arg) if(!arg[x]) { what=false; break;}
return what;
}
alert(is_falsy(ave));
Upvotes: 0
Reputation: 2090
You can test the following code here, play with the two sets of data. Note, that the default is 'ave_success', so the alert "Success !" will pop up when you will open the link.
Change "$.each(ave_success" to "$.each(ave_fail" to verify that the wrong data is rejected.
Note that an empty string '' is not considered as null
'' === null
will return false
var ave_fail = {
'a': '02',
'b': '04',
'c': '',
'd': '',
'f': '07'
};
var ave_success = {
'a': '02',
'b': '04',
'f': '07'
};
var total = 0
var success = true;
$.each(ave_success, function(key, value) {
var numbersA = total + value.length;
if (numbersA === 0) {
alert("Fail on index " + key + ' !');
success = false;
return false;
}
});
if (success) alert("Success !");
Upvotes: 1
Reputation: 224858
I would use a for in
loop; jQuery's jQuery.each
isn't well-suited to this situation.
var ave = {
'a': '02',
'b': '04',
'c': '',
'd': '',
'f': '07'
};
var success = true;
for(var x in ave) {
if(ave.hasOwnProperty(x)) {
if(ave[x] === '') {
success = false;
break;
}
}
}
if(success) {
alert('Pass!');
} else {
alert('Fail!');
}
Upvotes: 2
Reputation: 8338
Just set a global variable named failed
and alter its value if any of the properties are null:
var ave = {
'a': '02',
'b': '04',
'c': '',
'd': '',
'f': '07'
};
var failed = false;
var total = 0;
$.each(ave, function(key, value) {
var numbersA = total + value.length;
if (numbersA === 0) {
failed = true;
}
});
if (failed)
alert("Fail!");
Also, note that I'm using your method to check for null
values, which is incorrect. If you wanted to actually check for null
values, you would changed
if (numbersA === 0) {
failed = true;
}
to
if (numbersA === null) {
failed = true;
}
and then, if you wanted ave
to fail, you would need to change the empty strings to null
as well:
var ave = {
'a': '02',
'b': '04',
'c': null,
'd': null,
'f': '07'
};
Upvotes: 1