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


当前回答

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

其他回答

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

对于jQuery,它就像这样

if ($('input[name=gender]:checked').length > 0) {
    // do something here
}

让我把它分解成几部分,以便更清楚地解释。 jQuery从左到右处理事物。

input[name=gender]:checked

Input将其限制为输入标记。 [name=gender]将其限制为前一组中具有名称性别的标签。 :checked将其限制为前一组中选中的复选框/单选按钮。

如果您希望完全避免这种情况,可以在HTML代码中将其中一个单选按钮标记为已选中(checked="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;
            }
        }
    }

有一种非常复杂的方法可以用ECMA6和.some()方法验证是否选中了任意单选按钮。

Html:

<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />

和javascript:

let htmlNodes = document.getElementsByName('status');

let radioButtonsArray = Array.from(htmlNodes);

let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);

如果选中了一些单选按钮,isAnyRadioButtonChecked将为真,如果两个单选按钮都没有选中,则为假。

这对于具有相同名称的单选按钮是有效的,不需要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 });