In the following function it goes through the if and the else, why is that?
function test(){
$(".notEmpty").each(function() {
if($(this).val() === ""){
alert("Empty Fields!!");
return;
}
else{
AddRow_OnButtonClick('tblMedicationDetail',6);
}
});
}
Is there any if and else开发者_如何学运维 statement on jquery that I am not aware of?
AddRow_OnButtonClick is a function to add a new row with 6 textboxes which I am attaching a className 'notEmpty' if any of the text boxes are empty the function AddRow_OnButtonClick should not be called and an alert should pop up.
I dont know what am I doing wrong.
Thanks
The return
statement only returns from the function supplied to .each
. I suspect the problem you're having is that you want to return from test()
. As it is, after you return from the inner function you'll still apply the inner function to the rest of the elements.
If I'm right, and you want to break out of the .each()
altogether, put return false
instead (see jQuery docs).
Combining the existing two answers leads me to believe this will work:
var emptyFields = false;
function test(){
emptyFields = false;
$(".notEmpty").each(function() {
if($.trim($(this).val()) == "") {
emptyFields = true;
return false; // break out of the each-loop
}
});
if (emptyFields) {
alert("Empty Fields!!");
} else {
AddRow_OnButtonClick("tblMedicationDetail",6);
}
}
The basic idea is that you need to use your .each
call to only determine if a field is empty. After this, you can deal with the information using the if else
statement.
I've structured your code to make it a little more readable, but I'm not sure why both the if and the else are both being called:
function test(){
$(".notEmpty").each(function() {
if($(this).val() === ""){
alert("Empty Fields!!");
return;
} else {
AddRow_OnButtonClick("tblMedicationDetail",6);
}
});
}
if($(this).val() == ""){
2 equals signs not 3 - That MIGHT be your problem...?
精彩评论