IF and ELSE check is not working

Asked

Viewed 57 times

0

Guys, I’m trying to do the following, when you click on the button it checks if the fields are empty, if it’s all filled it hides the form, the problem it’s not falling into else of verification: if (formError) {...} else {...}.

When the form is completed correctly it should fall into the else.

Here is an excerpt from the code.

const fields = [...$('.form-group input')];

$.each(fields, function (index) {
    if ($(this).val() === "") {
        cardForm.removeClass('fadein').addClass('validate-error')
    }
});

const formError = $('.validate-error');

if (formError) {
    formError.bind('animationend', function (e) {
        if (e.originalEvent.animationName === 'nono') {
            formError.removeClass('validate-error').addClass('fadein');
        }
    });
} else {
    cardForm.removeClass('fadein').addClass('form-hide');
}

1 answer

4


The problem is in how you do the check. When you run this line:

const formError = $('.validate-error');

The jQuery will return an object with 0 children, but not a Undefined object, this will make it at all times enter into the verification of if. To solve your problem, change the check to:

if (formError.length > 0)

This will check if there is any wrong field, otherwise it will execute the else.

  • Gosh, aoskoaksokas, Thank you bro, every time I want to check if there’s something I have to use length > 0 ?, but thank you very much brother

  • 1

    @Boyprogrammer not necessarily, is that in this specific case, when you try to pull something with the jQuery selector, it will always return you a valid object, but if you have a variable/constant undefined, the check you tried to do would be correct. (:

  • 2

    @Bull programmer Can do so too: if (formError.length), because if it is greater than zero it will validate.

  • Ah got it, vlw guys

Browser other questions tagged

You are not signed in. Login or sign up in order to post.