jQuery中的动态单选按钮组验证 [英] Dynamical radio button group validation in jQuery

查看:60
本文介绍了jQuery中的动态单选按钮组验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最好的验证方法是确保检查每个组中的至少一个,因此在以下示例中,组是name1name2name3?

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?

示例

<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-我希望这是有道理的.

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.

推荐答案

您应使用 jquery .validate.js 库以帮助您解决此问题,请查看其演示

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

查看 jFiddle :这会为单选按钮找到所有不同的名称,然后遍历所有这些不同的名称分组并确保至少检查了一个,否则将发出警报.

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

这篇关于jQuery中的动态单选按钮组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆