Skip to content Skip to sidebar Skip to footer

Add Class If Input Is Empty And Remove It If Not

I would like to add a class if input is empty and remove it if it isn't. I initially had addClass(); so I tried using: .removeClass().addClass(); But it doesn't seem to update the

Solution 1:

You're trying to toggle the class. There's a method for that!

Quoting from the linked doc:

The second version of .toggleClass() uses the second parameter for determining whether the class should be added or removed. If this parameter's value is true, then the class is added; if false, the class is removed. In essence, the statement:

$( "#foo" ).toggleClass( className, addOrRemove );

is equivalent to:

if ( addOrRemove ) {
  $( "#foo" ).addClass( className );
} else {
  $( "#foo" ).removeClass( className );
}

Something along the lines of firstName.toggleClass("errorInput", firstName.val() === "") should work for your case.

Solution 2:

You can set some class to the input fields, or select em like this:

var firstName = $("#firstName");
var lastName = $("#lastName");

$('#button').click(function () {

  $('input').each(function(){

    if($this.val().trim()){
      $(this).addClass("errorInput");
    }
    else{
      $(this).removeClass("errorInput");
    }

  });

});

Solution 3:

Your code doesn't take into consideration the case where one input is empty and the other isn't.

https://jsfiddle.net/0tfenwto/2/

if(firstName.val() == "")
    firstName.addClass("errorInput");
else
    firstName.removeClass("errorInput")

if(lastName.val() == "")
    lastName.addClass("errorInput");
else
    lastName.removeClass("errorInput")

EDIT: Generic input length checker. https://jsfiddle.net/0tfenwto/3/

$('#button').click(function () {
    $('input').each(function(){
        var val = $(this).val();
        $(this).toggleClass("errorInput",val.length==0)
    })
});

Solution 4:

You forgot to add an else to your if.

if(){
    // add the class
 } else {
    // remove the class
 }

Here's an updated fiddle: https://jsfiddle.net/za7pkb74/1/

Post a Comment for "Add Class If Input Is Empty And Remove It If Not"