如何检查是否选择了具有相同名称的单选按钮

How do I check if either radio button with the same name is selected?

本文关键字:单选按钮 何检查 检查 选择 是否      更新时间:2023-09-26

我有两个同名的单选按钮。使用JavaScript,我如何检查,看看是否任何按钮是在焦点?这是我目前所做的;这是我的表单验证的一部分:

if (element.type == "radio") {
    if (element.checked === true) break;
    else error.push(element.name || element.id);
}

如果数组"error"中有任何内容,我就会知道没有选中复选框。但是,只有当两个无线电都被选中时,它才会显示"表单验证"。但是我只想知道是否有一个名字相同的被选中。我怎么做呢?

是一个单选按钮。将其中一个设置为默认选中,不可能同时选中两个,也不需要验证。

这是你如何用jQuery做到的:

$('input[name=test]').each(function() {
    if (this.checked) alert('yep');
})