2010-04-07 116 views
2

我想讓jquery驗證在多個字段上工作。原因是我添加了動態生成的字段,它們僅僅是一個電話號碼列表,從無到有儘可能多。一個按鈕添加另一個數字。使用jQuery驗證與多個相同名稱的字段

所以我想我會放在一起簡單的例子,隨後從接受的答案在下面的鏈接的概念:

Using JQuery Validate Plugin to validate multiple form fields with identical names

但是,它沒有做任何有用的事情。爲什麼它不起作用?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
        "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
    <script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/lib/jquery.delegate.js"></script> 
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script> 


<script> 
    $("#submit").click(function(){ 
    $("field").each(function(){ 
     $(this).rules("add", { 
     required: true, 
     email: true, 
     messages: { 
      required: "Specify a valid email" 
     } 
     }); 
    }) 
    }); 


    $(document).ready(function(){ 
    $("#myform").validate(); 
    }); 
</script> 

</head> 
<body> 

<form id="myform"> 
    <label for="field">Required, email: </label> 
    <input class="left" id="field" name="field" /> 
    <input class="left" id="field" name="field" /> 
    <input class="left" id="field" name="field" /> 
    <input class="left" id="field" name="field" /> 
    <br/> 
    <input type="submit" value="Validate!" id="submit" name="submit" /> 
</form> 

</body> 
</html> 

回答

5

此:$("field").each(function(){
應該是:$("[name=field]").each(function(){

而且你的ID應該是唯一的,你會得到不可預知的行爲時,這是不正確的。此外,你應該移動的規則的document.ready裏面添加,這樣的(這是現在所有的腳本):

$(function(){ 
    $("#myform").validate(); 
    $("[name=field]").each(function(){ 
    $(this).rules("add", { 
     required: true, 
     email: true, 
     messages: { 
     required: "Specify a valid email" 
     } 
    }); 
    }); 
}); 
+0

您的解決方案只是爲我工作以這種方式選擇輸入:$(「[名字^ = FOO ] [name $ = bar]「)。each(function()。這將選擇名稱屬性以」foo「開頭並以」bar「結尾的輸入,例如」foo_bar「,但它不適用於」 foob​​ar「... :) – ziiweb 2011-03-30 15:15:16

+1

@ user248959 - 對於'name =」foobar「'也應該正常工作(因爲它符合標準),你可以在這裏測試它:http://jsfiddle.net/nick_craver/fM52H/ – 2011-03-30 16:50:17

+0

@NickCraver,但它驗證我的第一個文本框只有 – 2014-07-01 09:33:49

相關問題