1

我想在页面第一次加载后检查表单的输入是否有值。如果是这样,那么添加一个类。

到目前为止,这是我的代码,

if( $('input').val() ) {
          $(this).addClass("correct");
    }

我需要检查长度吗?这是小提琴,http://jsfiddle.net/SFk3g/谢谢

4

2 回答 2

4

如果服务器端代码不是一个选项,您可以使用filter

$('input').filter(function() {
    return this.value;
}).addClass('correct');

一个普通的选择器也可以工作:

$('input[value!=""]').addClass('correct');
于 2013-04-30T23:12:57.103 回答
1

更新的小提琴:

http://jsfiddle.net/yhwYQ/

// Select all input elements, and loop through them.
$('input').each(function(index, item){
    // For each element, check if the val is not equal to an empty string.
    if($(item).val() !== '') {
        $(item).addClass('correct');   
    }
});

您可以选择所有输入元素,并遍历它们,然后应用您的检查。在这种情况下,您刚刚提到检查它们是否为空 - 这允许您根据业务逻辑的需要添加额外的检查。

于 2013-04-30T23:17:19.400 回答