我在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)
推荐文章
- 如何让一个按钮将我的页面重定向到另一个页面?
- 如何让元素被点击(对于整个文档)?
- 我如何检查如果一个变量是JavaScript字符串?
- 如何检测如果多个键被按下一次使用JavaScript?
- 如何通过history. pushstate获得历史变化的通知?
- 使用jQuery改变输入字段的类型
- 在JavaScript中,什么相当于Java的Thread.sleep() ?
- 使用jQuery以像素为整数填充或边距值
- 检查是否选择了jQuery选项,如果没有选择默认值
- Next.js React应用中没有定义Window
- 如何重置笑话模拟函数调用计数之前,每次测试
- 如何强制一个功能React组件渲染?
- 在javascript中从平面数组构建树数组
- 将Dropzone.js与其他字段集成到现有的HTML表单中
- 如何在AngularJS中观察路由变化?