1

I have a syntax error - I'm trying to add a class of 'error' if the input fields are blank. It's seems the error class is being applied even if the input fields have text, the logic looks correct to me. Can someone please assist?

$('input').each(function() {
    if($(this).val() == "") {
        $("input").addClass("error");
       return false;
    }
});
1
  • Initially they must have been left blank, that time the class is applied. But nothing happens after that. Did you forgot to apply class after text is entered ? Commented Feb 27, 2016 at 14:34

2 Answers 2

1

Try to use $(this) to while invoking .addClass(),

$('input').each(function() {
    if($(this).val() == "") {
        $(this).addClass("error");
    }
});

Or the best approach would be using using .filter(),

$('input').filter(function(){ 
   return this.value.trim() === "";
}).addClass("error");
Sign up to request clarification or add additional context in comments.

Comments

1

you should addClass to this, but better use toggleClass to also remove error if input got filled:

$('input').each(function() {
    $(this).toggleClass('error', this.value == "");
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.