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


当前回答

您可以使用这个简单的脚本。 您可以有多个名称相同但值不同的单选按钮。

var checked_gender = document.querySelector('input[name = "gender"]:checked');

if(checked_gender != null){  //Test if something was checked
alert(checked_gender.value); //Alert the value of the checked.
} else {
alert('Nothing checked'); //Alert, nothing was checked.
}

其他回答

if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)

http://www.somacon.com/p143.php/

function getCheckedValue(radioObj) {
    if(!radioObj)
        return "";
    var radioLength = radioObj.length;
    if(radioLength == undefined)
        if(radioObj.checked)
            return radioObj.value;
        else
            return "";
    for(var i = 0; i < radioLength; i++) {
        if(radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

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

HTML:

<label class="block"><input type="radio" name="calculation" value="add">+</label>
<label class="block"><input type="radio" name="calculation" value="sub">-</label>
<label class="block"><input type="radio" name="calculation" value="mul">*</label>
<label class="block"><input type="radio" name="calculation" value="div">/</label>

<p id="result"></p>

JAVAScript:

var options = document.getElementsByName("calculation");

for (var i = 0; i < options.length; i++) {
    if (options[i].checked) {
        // do whatever you want with the checked radio
        var calc = options[i].value;
        }
    }
    if(typeof calc == "undefined"){
        document.getElementById("result").innerHTML = " select the operation you want to perform";
        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选择器的错误,我已经包括了引号,虽然你可以省略它们,在某些情况下你不能这样做,所以最好把它们留在。