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


当前回答

表单

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

这个脚本

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

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

其他回答

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

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/

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

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

注意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()不返回单选输入的检查值,正如您所期望的那样——它返回第一个单选按钮的值。