2013-03-19 69 views
-4

我的HTML有這樣的事情:JavaScript驗證使用jQuery

<html> 
<table class="MyTable" id="idMyTable"> 
<tr> 
<td> 
<select class="mySelect"> 
<option>A</option> 
<option>B</option> 
</select> 
</td> 
<td> 
<input type="text" class="myInput"/> 
</td> 
<tr> 
<tr> 
<td> 
<select class="mySelect"> 
<option>A</option> 
<option>B</option> 
</select> 
</td> 
<td> 
<input type="text" class="myInput"/> 
</td> 
<tr> 
</table> 
<input type="button" value="Check" onclick="validate()"/> 
</html> 

裏面的validate方法我想如果用戶選擇的B選項,那麼相應的輸入字段必須不能爲空檢查。這怎麼可以使用jQuery來完成?

感謝任何幫助。

+3

你試過了什麼? – 2013-03-19 07:13:12

+0

什麼都沒有。我正在學習jQuery。 :) – 2013-03-19 07:15:11

+0

學習和嘗試必須全都在同一個步驟。不要嘗試任何事情學習是浪費谷歌搜索給了你很多想法 – NetStarter 2013-03-19 07:16:30

回答

0

請添加這樣的第一選擇正確評估值..

<select class="mySelect"> 
<option value="A">A</option> 
<option value="B">B</option> 
</select> 
And here is the logic goes under validation method 
$(".mySelect").each(function(){ 
    if($(this).val() == "B") 
    { 
    if($.trim($(this).closest("myInput").val()) == '') 
    { 
     // Validation logic here 
    } 
    } 
}); 

如果你不希望有價值的選項作爲親參看上面的內容,然後使用jQuery檢查選項的選定文本。

1

你可以做這樣的事情:

$(".mySelect").each(function(){ 
    if($(this)[0].selectedIndex > 0) 
    { 
     if($(this).closest(".myInput").val() == '') 
     { 
      alert("this input is not valid"); 
      return false 
     } 
    } 
}); 
+0

感謝您的輸入。它幫助進行了一些小修改。 $(「。mySelect」)。each(function(){if($(this)[0] .selectedIndex> 0) \t if($。trim($(this).closest(「。myInput」 ).val()).length <= 0) { alert(「this input is valid」); return false } } }); – 2013-03-19 08:34:04

+0

如果您覺得如此,請將其標記爲已接受的答案。 – 2013-03-19 08:41:43