如果输入为空则添加 class 否则将其删除

Add class if input is empty and remove it if not

如果输入为空,我想添加一个 class,如果不是,我想将其删除。我最初有 addClass(); 所以我尝试使用:

.removeClass().addClass();

但它似乎没有在单击按钮时更新 class。

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

您正在尝试 toggle the class。有一个方法!

引用链接文档:

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

类似于 firstName.toggleClass("errorInput", firstName.val() === "") 的内容应该适合您的情况。

您忘记在 if 中添加 else。

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

这是更新后的 fiddle:https://jsfiddle.net/za7pkb74/1/

您的代码没有考虑一个输入为空而另一个不为空的情况。

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

编辑:通用输入长度检查器。 https://jsfiddle.net/0tfenwto/3/

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

您可以将一些 class 设置到输入字段,或者像这样 select em:

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

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

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

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

  });

});