我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?
当前回答
这对于具有相同名称的单选按钮是有效的,不需要JQuery。
var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked })[0];
如果我们正在讨论复选框,并且我们想要一个列表,其中选中的复选框共享一个名称:
var x = Array.prototype.filter.call(document.getElementsByName('checkThing'), function(x) { return x.checked });
其他回答
这是我为了解决这个问题而创建的效用函数
//define radio buttons, each with a common 'name' and distinct 'id'.
// eg- <input type="radio" name="storageGroup" id="localStorage">
// <input type="radio" name="storageGroup" id="sessionStorage">
//param-sGroupName: 'name' of the group. eg- "storageGroup"
//return: 'id' of the checked radioButton. eg- "localStorage"
//return: can be 'undefined'- be sure to check for that
function checkedRadioBtn(sGroupName)
{
var group = document.getElementsByName(sGroupName);
for ( var i = 0; i < group.length; i++) {
if (group.item(i).checked) {
return group.item(i).id;
} else if (group[0].type !== 'radio') {
//if you find any in the group not a radio button return null
return null;
}
}
}
下面是扩展后的解决方案,即不继续提交,并在未选中单选按钮时发送警报。当然,这意味着你必须在一开始就不检查它们!
if(document.getElementById('radio1').checked) {
} else if(document.getElementById('radio2').checked) {
} else {
alert ("You must select a button");
return false;
}
只要记住在每个单选按钮的表单中设置id ('radio1','radio2'或任何你叫它的名字),否则脚本将无法工作。
返回单选按钮中所有选中的元素
Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);
这也是可行的,避免调用元素id,而是将其作为数组元素调用。
下面的代码是基于这样一个事实:一个名为radiobuttons组的数组是由radiobuttons元素组成的,它们的顺序与html文档中声明的相同:
if(!document.yourformname.yourradioname[0].checked
&& !document.yourformname.yourradioname[1].checked){
alert('is this working for all?');
return false;
}
一种简单的JavaScript方式
var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio' && radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
}
}