Dynamical radio button group validation in jQuery

ⅰ亾dé卋堺 提交于 2019-12-05 01:23:58

问题


What is the best way to validate to ensure at least one in every group is checked, so in the following example groups are name1, name2, name3?

Example

<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">

I know I can wrap a div around each one and then check each radio button in the div, but I am looking for a more dynamic solution. So, if in future more radio buttons are added, the jQuery code would not need to be altered or the divs would not need to be added - I hope this makes sense.


回答1:


You should use jquery.validate.js library to help you solve this question, check out their demo

If you use the library it would be as simple as,

<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">

Check out the jFiddle: This finds all the different names for radio buttons and then runs through all those different groups and makes sure that there is at least one checked, if not it will throw an alert.

$('#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();
        }
    }
});



回答2:


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

Or

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

You could also do something a little more dynamic if you like:

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++;
}


来源:https://stackoverflow.com/questions/8229844/dynamical-radio-button-group-validation-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!