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


当前回答

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

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

其他回答

我使用展开运算符和some来检查数组中至少有一个元素通过了测试。

我为谁分担关心。

var checked =[..文档.getElementsByName(“性别”).有些(c=>c.checked); 控制台日志(检查); <输入类型=“收音机”,性别“检查值=“男性”/> Male <输入类型=“无线电”

注意jQuery在获取无线电输入值时的行为:

$('input[name="myRadio"]').change(function(e) { // Select the radio input group

    // This returns the value of the checked radio button
    // which triggered the event.
    console.log( $(this).val() ); 

    // but this will return the first radio button's value,
    // regardless of checked state of the radio group.
    console.log( $('input[name="myRadio"]').val() ); 

});

因此$('input[name="myRadio"]').val()不返回单选输入的检查值,正如您所期望的那样——它返回第一个单选按钮的值。

让我们假设你有这样的HTML

<input type="radio" name="gender" id="gender_Male" value="Male" />
<input type="radio" name="gender" id="gender_Female" value="Female" />

对于客户端验证,这里有一些Javascript来检查选择了哪个:

if(document.getElementById('gender_Male').checked) {
  //Male radio button is checked
}else if(document.getElementById('gender_Female').checked) {
  //Female radio button is checked
}

根据标记的确切性质,可以使上面的操作更有效,但这应该足以让您入门。


如果你只是想看看页面上是否有单选按钮被选中,PrototypeJS会让你很容易做到。

下面是一个函数,如果页面上至少有一个单选按钮被选中,该函数将返回true。同样,这可能需要根据特定的HTML进行调整。

function atLeastOneRadio() {
    return ($('input[type=radio]:checked').size() > 0);
}

对于服务器端验证(请记住,您不能完全依赖Javascript进行验证!),这取决于您所选择的语言,但是您可以检查请求字符串的性别值。

给单选按钮,相同的名称,但不同的id。

var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
  //condition
  final_answer = verified1;
}
else
{
  if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
    //condition
    final_answer = verified2;
   }
   else
   {
     return false;
   }
}

我只是想确保一些东西被选中(使用jQuery):

// html
<input name="gender" type="radio" value="M" /> Male <input name="gender" type="radio" value="F" /> Female

// gender (required)
var gender_check = $('input:radio[name=gender]:checked').val();
if ( !gender_check ) {
    alert("Please select your gender.");
    return false;
}