如果输入为空,则添加类;如果输入为空,则将其删除 [英] Add class if input is empty and remove it if not

查看:107
本文介绍了如果输入为空,则添加类;如果输入为空,则将其删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

JSFiddle

推荐答案

您正尝试切换类.有一种方法!

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

从链接文档中引用:

.toggleClass()的第二个版本将第二个参数用于 确定是应该添加还是删除类.如果这 参数的值为true,则添加类;如果为假,则 类已删除.本质上,该语句:

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

等效于:

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

符合firstName.toggleClass("errorInput", firstName.val() === "")的情况应该适用于您的情况.

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

这篇关于如果输入为空,则添加类;如果输入为空,则将其删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆