0

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

2
  • 2
    You are removing a class and then adding it right back in. Commented Feb 27, 2016 at 0:56
  • Yuck, it bothers me when the titles don't reflect the content. Title doesn't say anything about "on click" :( Commented Jul 17, 2018 at 19:26

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

7 Comments

firstName.toggleClass("errorInput", firstName.val() === "")
toggle just toggles the class on button click regardless of the input being empty or nto
Toggle can accept a conditional argument indicating whether to toggle the class on or off.
@Hamms Put that in the answer
@Hamms woah... didn't know toggle class accepted another parameter. Thank you!!
|
4

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");
    }

  });

});

Comments

2

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)
    })
});

3 Comments

I would rather avoid that many if blocks. I have many input fields and that is why my if statement has multiple checks on one line
Avoiding code duplication is good, however misrepresenting error states is not good. Check my edit for a generic solution.
@user4756836 - So you'll display your First Name field as being in an error state even though it isn't just to avoid an extra if/else? Fortunately there is a shorter way to code it, without the if/else, but even if there wasn't you really should write as much code as needed to avoid confusing the user.
0

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/

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.