Javascript 检查单选按钮是否被选中?

问题描述:

我找到了可以执行此操作的脚本,但它们只能使用一个单选按钮名称,我有 5 个不同的单选按钮集.我如何检查它现在是否被选中我尝试提交表单

I have found scripts that do it, but they only work with one radio button name, i have 5 different radio button sets. How can i check if its selected right now i tried on form submit

if(document.getElementById('radiogroup1').value=="") {
        alert("Please select option one");
        document.getElementById('radiogroup1').focus();
        return false;
    }

不起作用.

如果您决心使用标准 JavaScript,那么:

If you have your heart set on using standard JavaScript then:

函数定义

var isSelected = function() {
    var radioObj = document.formName.radioGroupName;

    for(var i=0; i<radioObj.length; i++) {
        if( radioObj[i].checked ) {
            return true;
        }
    }

    return false;
};

使用

if( !isSelected() ) {
    alert('Please select an option from group 1 .');
}   

我建议使用 jQuery.它有很多选择器选项,当一起使用时,可以将大部分代码简化为一行.

I'd suggest using jQuery. It has a lot of selector options which when used together simplify the much of the code to a single line.

替代解决方案

if( $('input[type=radio][name=radioGroupName]:selected').length == 0 ) {
    alert('Please select an option from group 1 .');
}