Amra
Amra

Reputation: 25180

jquery if else, why does not work?

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

Upvotes: 0

Views: 2641

Answers (4)

Codesleuth
Codesleuth

Reputation: 10541

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.

Upvotes: 1

Stefan P
Stefan P

Reputation: 1043

if($(this).val() == ""){

2 equals signs not 3 - That MIGHT be your problem...?

Upvotes: 0

Skilldrick
Skilldrick

Reputation: 70819

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).

Upvotes: 3

Barrie Reader
Barrie Reader

Reputation: 10713

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);
        }
    });
}

Upvotes: 0

Related Questions