Dynamical radio button group validation in jQuery

扶醉桌前 提交于 2019-12-03 17:04:40
Jose Vega

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();
        }
    }
});
$('[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++;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!