如何validation多个单选按钮

如何validation多个单选按钮。 所有这些单选按钮动态生成。

                

试试这个http://jsfiddle.net/aamir/r9qR2/

由于每个组都有不同的名称属性,因此您必须对每组单选按钮进行validation。

 if($('input[name="answer_option1"]:checked').length === 0) { alert('Please select one option'); } 

如果您拥有无限数量的群组。 试试这个http://jsfiddle.net/aamir/r9qR2/2/

  //Make groups var names = [] $('input:radio').each(function () { var rname = $(this).attr('name'); if ($.inArray(rname, names) == -1) names.push(rname); }); //do validation for each group $.each(names, function (i, name) { if ($('input[name="' + name + '"]:checked').length == 0) { console.log('Please check ' + name); } }); 

如果您只想为所有组显示1个错误。 试试这个http://jsfiddle.net/aamir/r9qR2/4/

尝试这个新的小提琴http://jsfiddle.net/Hgpa9/3/

 $(document).on("click","#validate", 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(); } } }); 
 var names = [] $('input[name^="answer_option"]').each(function() { var rname = $(this).attr('name'); if ($.inArray(rname, names) == -1) names.push(rname); }); $.each(names, function (i, name) { if ($('input[name="' + name + '"]:checked').length == 0) { console.log('Please check ' + name); } });