javascriptjqueryinputaddclassremoveclass

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 class on the click of the button.

HTML:

<input id="firstName" type="text" />
<input id="lastName" type="text" />
<a href="#" id="button">SEND</a>

jQuery:

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

$('#button').click(function () {
    if(firstName.val() == "" || lastName.val() == ""){
        firstName.removeClass("errorInput").addClass("errorInput");
        lastName.removeClass("errorInput").addClass("errorInput");
    }

if ($(":input").hasClass("errorInput")) {
        alert("false");
    } else {
        alert("true");
    }
});

JSFiddle


Solution

  • 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.