Reinis
Reinis

Reputation: 93

jquery else if statement doesn't work

I want to show a warning message if user does not complete entire form but it seems not to work as I want. The jQuery .each method only collects data from the first input field. If I leave the first field empty it works correctly but if I fill only the first field and leave other fields empty it shows success which is wrong.

// send message on click
$("#submit").click(function() {

    // store values
    var data = $("#form").serialize();

    $(":input, textarea").each(function() {

        // if empty show warning
        if ( $(this).val() === "" ) {
            $(".message-fail").fadeIn(500);
        }

        // if not empty send message
        else if ( !$(this).val() ) {
                $.ajax({
                    type: "POST",
                    url: "mail.php",
                    data: data,
                    success: function() {
                        $(".message-sent").fadeIn(500);
                    }
                });
        }

    });

});

Upvotes: 0

Views: 665

Answers (3)

thecodeparadox
thecodeparadox

Reputation: 87073

You can do following process:

BUT I THINK YOU DON'T NEED AJAX FOR EVERY FIELD

if ($.trim(this.value).length) { // if value exists
    $(".message-fail").fadeIn(500);
} else { // if no value exists, here no need to elseif
    $.ajax({
        type: "POST",
        url: "mail.php",
        data: data,
        success: function() {
            $(".message-sent").fadeIn(500);
        }
    });
}

Explanation:

$.trim(this.value) -> check for value exists

or can also use (first one is better)

$.trim($(this).val()).length -> checks for value exists

Upvotes: 1

refeline
refeline

Reputation: 39

you need to place "else" outside of "each", because first valid input will post form :) make a flag variable, make checks inside of each... but it's better to use simple loop. and after checks complited make another check of your flag and post if it's ok

Upvotes: 0

Gaurav Agrawal
Gaurav Agrawal

Reputation: 4431

in this line else if ( !$(this).val() ) there is wrong condition i.e. !$(this).val() please make it correct it will work....

Upvotes: 0

Related Questions