我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?
当前回答
我只是想确保一些东西被选中(使用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;
}
其他回答
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;
}
注意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()不返回单选输入的检查值,正如您所期望的那样——它返回第一个单选按钮的值。
返回单选按钮中所有选中的元素
Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);
只是试图改进Russ Cam的解决方案与一些CSS选择器糖扔在香草JavaScript。
var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;
这里不需要jQuery, querySelectorAll现在已经得到了足够广泛的支持。
编辑:修正了一个css选择器的错误,我已经包括了引号,虽然你可以省略它们,在某些情况下你不能这样做,所以最好把它们留在。
表单
<form name="teenageMutant">
<input type="radio" name="ninjaTurtles"/>
</form>
这个脚本
if(!document.teenageMutant.ninjaTurtles.checked){
alert('get down');
}
小提琴:http://jsfiddle.net/PNpUS/