2011-08-12 24 views
3

我使用jQuery驗證插件(http://bassistance.de/jquery-plugins/jquery-plugin-validation/驗證只針對任何特定的幾個字段提交按鈕

我已經在我面前一個非常奇怪的場景。

我有一個形式,具有5種不同的提交按鈕

<form id="frm1" name="frm1" method="post" action="save.php"> 
    ------- input fields here--- 
    <input type="submit" name="submit" value="update account info"> 

    ------- input fields here--- 
    <input type="submit" name="submit" value="update address info"> 

    ------- input fields here--- 
    <input type="submit" name="submit" value="update credit-card info"> 

    ------- input fields here--- 
    <input type="submit" name="submit" value="update bank info"> 

    ------- input fields here--- 
    <input type="submit" name="submit" value="update other info"> 
</form> 

現在,對於每一個提交按鈕,我需要驗證幾個字段(而不是所有字段)

稱之爲「更新帳戶信息」提交,我需要驗證下列輸入字段與以下ID:

cust_fname 
cust_lname 
cust_age 

說‘更新其他信息’提交,我需要驗證下列輸入字段與以下ID:

married 
childerns 

我該如何實現以下目標?

回答

3

創建5個單獨的窗體是最簡單的方法。然後,您可以將不同的特定驗證綁定到每個表單。

或者您可以將驗證綁定到提交按鈕上的每次點擊。 假設你更新你的提交按鈕到:

<input type="submit" id="button_1" name="submit" value="update account info"> 

然後使用jQuery你可以用綁定的:

$("#button_1").live("click", function() { 
    $("#frm1").validate({ 
     rules: { 
      cust_fname: "required", // of course set different options for every field 
      cust_lname: "required", 
      cust_age: "required" 
     } 
    }); 
}); 

併爲每個按鈕做到這一點。

編輯:現場已被棄用。

$("#button_1").on("click", function() { 
    $("#frm1").validate({ 
     rules: { 
      cust_fname: "required", // of course set different options for every field 
      cust_lname: "required", 
      cust_age: "required" 
     } 
    }); 
}); 
+1

['live()'已被棄用,因爲jquery 1.7並在1.9中刪除](http://api.jquery.com/live/)。只需使用['on()'](http://api.jquery.com/on/)。 –