2011-11-22 29 views
5

什麼是驗證以確保每個組中至少有一個被選中的最佳方式是什麼,因此在下面的示例中,組是name1,name2, name3jQuery中的動態單選按鈕組驗證

<input type="radio" name="name1"> 
<input type="radio" name="name1"> 
<input type="radio" name="name1"> 

<input type="radio" name="name2"> 
<input type="radio" name="name2"> 
<input type="radio" name="name2"> 

<input type="radio" name="name3"> 
<input type="radio" name="name3"> 
<input type="radio" name="name3"> 

我知道我可以換一個div每一個周圍,然後在div檢查每個單選按鈕,但我期待一個更動態的解決方案。所以,如果將來會增加更多的單選按鈕,那麼jQuery代碼就不需要修改,或者div也不需要添加 - 我希望這是有道理的。

+0

你爲什麼不添加一個類或id屬性爲每個組?你可以使用該驗證 – Kishore

回答

8

您應該使用jquery.validate.js庫來幫你解決這個問題,看看他們的demo

如果您使用的庫那將是一樣簡單,

<input type="radio" name="name1" validate="required:true"> 
<input type="radio" name="name1"> 
<input type="radio" name="name1"> 

<input type="radio" name="name2" validate="required:true"> 
<input type="radio" name="name2"> 
<input type="radio" name="name2"> 

退房的jFiddle:此發現所有不同的單選按鈕的名稱,然後遍歷所有不同的組,並確保至少有一個檢查,如果不是,它會引發警報。

$('#button').click(function() { 
    var names = []; 

    $('input[type="radio"]').each(function() { 
     // Creates an array with the names of all the different checkbox group. 
     names[$(this).attr('name')] = true; 
    }); 

    // Goes through all the names and make sure there's at least one checked. 
    for (name in names) { 
     var radio_buttons = $("input[name='" + name + "']"); 
     if (radio_buttons.filter(':checked').length == 0) { 
      alert('none checked in ' + name); 
     } 
     else { 
      // If you need to use the result you can do so without 
      // another (costly) jQuery selector call: 
      var val = radio_buttons.val(); 
     } 
    } 
}); 
+0

謝謝你是非常有用的解決方案 - 我不想使用插件來驗證單選按鈕 –

+0

我添加了一些更多的原始檢查代碼。 –

+1

什麼名稱[$(this).attr('name')] = true;做? – contactmatt

1
$('[name="name1"]:checked').length != 0 

或者

$('[name="name1"]').is(':checked') 

你也可以做一些更動態的,如果你喜歡:

var i = 1; 
while ($('[name="name'+i+'"]').length != 0) { 
    if ($('[name="name'+i+'"]').is(':checked')) { 
     // at least one is checked in this group 
    } else { 
     // none are checked 
    } 
    i++; 
} 
+1

如果收音機的名字是這種格式,非常甜蜜的解決方案,但我會認爲,作爲開發人員,他會想給他們一個更重要的名字。 –