2011-03-17 123 views
0

我有一個關於十個字段的搜索表單。它們中的幾個是「文本」類型的輸入元素,並且它們中的幾個是選擇框。用戶應至少選擇一個條件進行搜索。對於所有10個字段,我可以編寫類似「if input1!= null & & input2!= null ...」的內容來檢查用戶是否至少選擇了一個條件。

但我覺得這是很多代碼。有沒有我可以只寫一行代碼來滿足這個要求(即用戶應該選擇至少一個搜索條件)使用jQuery?JQuery表單驗證問題

回答

2
$('input[value!=""]').length 

這顯示了在其中有文本(與「」)不同的輸入字段的數量。 Try it here

2

您應該嘗試JQuery validate插件。它非常易於使用。

+0

+1,那是另一個不錯的選擇。 – mattsven 2011-03-17 19:41:09

0
$('input, select').each(function(){ 
var current = $(this); 
if(current.val() == //yourcriteria//) { 
    //do stuff! 
} 
}); 
0

喜歡的東西

var somethingSelectedInEach = true; 

$("select").each(function(i, el){ 
    if($(this).val() == null){ 
     somethingSelectedInEach = false; 
     return false; 
    } 
}); 

if(somethingSelectedInEach){ 
    alert("Yaay! You selected something in each select!"); 
} else { 
    alert("Booo. You forgot to select something in each select!"); 
}