如何验证两组单选按钮 [英] How to validate two sets of radio buttons

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

问题描述

我有两组单选按钮,我想使用两组中的返回值并进行验证.用户必须从两组中至少选择一个值;用户也可以从两个组中选择两个值.我无法发出警报,提交时我在页面上使用错误标签. 我不知道的是,如何让用户自由选择任何单选按钮,并且即使选择了一个单选按钮,错误也会消失.

I have two sets of radio buttons and I want to use return value from both sets and validate. User has to select at least one value from the two groups; user can select two values from two groups as well. I cannot throw an alert, I am using labels for errors on the page upon submission. What I cannot figure out is, how to give user freedom to select any radio button and error to go away if even one radio button is selected.

这是我的小提琴,现在不再工作了. http://jsfiddle.net/pQNNU/

Here is my fiddle which is not working anymore. http://jsfiddle.net/pQNNU/

我也使用了这个:

$('#submit').click(function() {
    var v1 = $('input:radio[name="attending_day_1"]:checked').val();
    var v2 = $('input:radio[name="attending_day_2"]:checked').val();

    if (!v1 && !v2 ) {
        $('.validation-error').html('*Please select attending day');
return false;
    } 
});

但这不会让我的其他字段通过validate函数进行验证.

But this does not let my other fields validate from validate function.

推荐答案

具有相同名称的输入(在同一个组内)的工作原理是,当您单击一个单选按钮时-其余所有具有相同名称的按钮将变得不受控制. 要允许多个选择-您必须给它们指定不同的名称.

The idea how inputs with the same names work (means within the same group) is that when you click on one radio button - all the rest with the same names will become unchecked. To allow multiple selections - you'll have to give them different names.

要执行验证-例如,您可以将输入集包装到带有ID的div中.然后检查该div内的输入中是否至少有一个选中的项目.

To perform validation - you can wrap your set of inputs into div with id, for example. And then check if there is at least one checked item in inputs that are inside that div.

实际上,更好的一种变体是如果需要多个选择,请使用复选框.单选按钮的目的是另一项任务.但是谁知道你的目标是什么:)

Actually, the better one variant is to use check boxes if you need multiple selections. Radio buttons purpose is for another tasks. But who knows what's your target :)

简短示例在这里: http://jsbin.com/zacomuve/1/edit

希望这是您所需要的.

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

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