2013-02-18 86 views
4

我使用的是jQuery Validation Plugin,我希望能夠動態添加和刪除3個單選按鈕組的驗證。將jQuery驗證規則添加到單選按鈕組

我能夠動態地添加和使用下面的示例代碼從文本字段中輸入驗證刪除:

<script type="text/javascript"> 
    $(document).ready(function(){ 

     //Add Requird Validation 
     $("#inputTextField").rules("add", "required"); 

     //Remove Required Validation 
     $("#inputTextField").rules("remove", "required"); 

    }); 
</script> 

是否有可能做單選按鈕一樣嗎?

+0

您是否嘗試添加規則並對其進行測試? – 2013-02-18 21:31:55

+0

我該如何添加它?我無法像使用文本字段一樣使用元素ID。 – AlGallaf 2013-02-18 21:38:24

+1

您在技術上可以使用一個ID,前提是您的每個無線電輸入都有唯一的ID。我相信在一個單選按鈕組上添加一個必需的狀態,您只需將它添加到其中一個狀態即可。試試看,如果它不起作用,請修改您的問題,詳細說明您嘗試的內容以及您的表單的外觀。 – 2013-02-18 21:43:15

回答

3

您發佈的代碼將正常工作。但是,必須在.validate()之後來到,並且每個input必須包含name屬性,即使您未通過name定位也是如此。

HTML

<form id="myform"> 
    <input type="text" name="field" id="inputTextField" /> <br/> 
</form> 

jQuery的

$(document).ready(function() { 

    $('#myform').validate({ 
     // other options & rules 
    }); 

    // must come afer validate() 
    $("#inputTextField").rules("add", { 
     required: true 
    }); 

}); 

演示:http://jsfiddle.net/fnKWD/

Is it possible to do the same with radio buttons?

考爾中se,只需按名稱或其他任何其他valid jQuery selector

$('input[name="myname"]') 

HTML

<input type="radio" name="myname" value="0" /> 
<input type="radio" name="myname" value="2" /> 
<input type="radio" name="myname" value="5" /> 

演示http://jsfiddle.net/LkJZw/

+0

我將相同的概念應用於單選按鈕組,但最終出現以下錯誤:未捕獲的TypeError:無法讀取未定義的屬性「設置」 – AlGallaf 2013-02-18 22:09:23

+0

@ looi76,我看不到您的代碼,因此我不知道您的「重新做錯了,但它在這裏工作:http://jsfiddle.net/LkJZw/ – Sparky 2013-02-18 22:15:41

+0

@ looi76,請參閱我編輯使用'無線電'按鈕的工作演示。 – Sparky 2013-02-18 23:11:42