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


当前回答

表单

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

这个脚本

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

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

其他回答

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

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

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

表单

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

这个脚本

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

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

这对于具有相同名称的单选按钮是有效的,不需要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 });
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)