2

I am doing a form validation, and I wish that all inputs that were empty adds the class "error", now I got only one at a time.

jQuery

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

JSFIDDLE

2 Answers 2

3

You might also want to restore the nonerror and check for whitespaces: demo

var inp = $('.text-input');                     // Cache your selectors

inp.blur(function () {                          // On blur...
    inp.removeClass('error').filter(function(){ // Remove error classes. Filter
       return !$.trim(this.value);              // to return el. without value
    }).addClass('error');                       // and assign error class.
});

Another way to do it: demo

var inp = $('.text-input');

function err(){
  $.each(inp, function(){
    $(this).toggleClass('error', !$.trim(this.value));
 });  
}

inp.blur(err);

Using the classic if demo

var inp = $('.text-input');

function err(){
  $.each(inp, function(){
    if(!$.trim(this.value)){
      $(this).addClass('error');
      // more stuff
    }else{
      $(this).removeClass('error');
      // more stuff
    }
 });  
}

inp.blur(err);
Sign up to request clarification or add additional context in comments.

4 Comments

Perfect guy, just that if I want to put this in a "if" would be like? Thanks.
Why remove the class for ALL input boxes when only one changes its value?
@RokoC.Buljan orly, have you seen how my answer solves it? :)
@Jack ...beautifully?! ;)
1

The decision of adding the error class should also happen at the start; to do this, you can write a small function that will be run either at the start or whenever the blur event occurs.

Also, you can simplify the logic of adding or removing the error class by using .toggleClass().

function updateInputClass()
{
    $(this).toggleClass('error', $.trim(this.value) == '');
}

$(".text-input")
  .blur(updateInputClass)
  .each(updateInputClass)

Demo

2 Comments

+1 for your designing skills _°g°_ <- teddy is watching you ;)
@RokoC.Buljan Haha, much obliged Sir :)

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.