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


当前回答

给单选按钮,相同的名称,但不同的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;
   }
}

其他回答

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

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

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

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)

表单

<form name="teenageMutant">
  <input type="radio" name="ninjaTurtles"/>
</form>

这个脚本

if(!document.teenageMutant.ninjaTurtles.checked){
  alert('get down');
}

小提琴:http://jsfiddle.net/PNpUS/

Try

[...myForm.sex].filter(r=>r.checked)[0].value

函数检查() { 设 v= ([...myForm.].filter(r=>r.checked)[0] ||{}).value ; 控制台.log(v); } <表单 id=“我的表单”> <输入名称=“性别”类型=“无线电”值=“男人”>男人 <输入名称=“性别”类型=“无线电”值=“女人”>女人 </form> <br><button onClick=“check()”>Check</button>