2013-04-30 40 views
1

我想檢查表單的輸入是否有值,一旦頁面加載第一次。如果是這樣,然後添加一個類。jQuery,檢查當第一次加載頁面時是否有值<input>

這裏是我的代碼,到目前爲止,

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

我是否需要進行檢查的長度?這裏的小提琴,http://jsfiddle.net/SFk3g/謝謝

+0

爲什麼不在服務器端添加正確的類? – 2013-04-30 23:11:02

+0

答案很可能是由業務需求驅動的,例如*作爲有效輸入值的資格是什麼?* – Madbreaks 2013-04-30 23:11:09

+0

您是否想要檢查每個輸入元素並將該類添加到包含某些元素的類中? – nnnnnn 2013-04-30 23:14:48

回答

4

如果服務器端代碼是不是一種選擇,你可以使用filter

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

一個普通的選擇也可能工作:

$('input[value!=""]').addClass('correct'); 
+0

謝謝,這工作完美。 – Richard 2013-04-30 23:20:47

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

您可以選擇所有輸入元素,並循環遍歷它們,然後應用您的檢查。在這種情況下,您剛剛提到要檢查它們是否爲空 - 這允許您根據需要添加業務邏輯所需的其他檢查。

相關問題