我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?


当前回答

mootools (http://mootools.net/docs/core/Element/Element)

html:

<input type="radio" name="radiosname" value="1" />
<input type="radio" name="radiosname" value="2" id="radiowithval2"/>
<input type="radio" name="radiosname" value="3" />

js:

// Check if second radio is selected (by id)
if ($('radiowithval2').get("checked"))

// Check if third radio is selected (by name and value)
if ($$('input[name=radiosname][value=3]:checked').length == 1)


// Check if something in radio group is choosen
if ($$('input[name=radiosname]:checked').length > 0)


// Set second button selected (by id)
$("radiowithval2").set("checked", true)

其他回答

下面是扩展后的解决方案,即不继续提交,并在未选中单选按钮时发送警报。当然,这意味着你必须在一开始就不检查它们!

if(document.getElementById('radio1').checked) {
} else if(document.getElementById('radio2').checked) {
} else {
  alert ("You must select a button");
  return false;
}

只要记住在每个单选按钮的表单中设置id ('radio1','radio2'或任何你叫它的名字),否则脚本将无法工作。

HTML代码

<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >

Javascript代码:

var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
    if(off_payment_method[i].checked) {
        ischecked_method = true;
        break;
    }
}
if(!ischecked_method)   { //payment method button is not checked
    alert("Please choose Offline Payment Method");
}

这也是可行的,避免调用元素id,而是将其作为数组元素调用。

下面的代码是基于这样一个事实:一个名为radiobuttons组的数组是由radiobuttons元素组成的,它们的顺序与html文档中声明的相同:

if(!document.yourformname.yourradioname[0].checked 
   && !document.yourformname.yourradioname[1].checked){
    alert('is this working for all?');
    return false;
}

只是试图改进Russ Cam的解决方案与一些CSS选择器糖扔在香草JavaScript。

var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;

这里不需要jQuery, querySelectorAll现在已经得到了足够广泛的支持。

编辑:修正了一个css选择器的错误,我已经包括了引号,虽然你可以省略它们,在某些情况下你不能这样做,所以最好把它们留在。

这是我为了解决这个问题而创建的效用函数

    //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;
            }
        }
    }