我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?
当前回答
该代码将在提交表单时提醒所选单选按钮。它使用jQuery来获取所选的值。
$("form").submit(function(e) { e.preventDefault(); $this = $(this); var value = $this.find('input:radio[name=COLOR]:checked').val(); alert(value); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input name="COLOR" id="Rojo" type="radio" value="red"> <input name="COLOR" id="Azul" type="radio" value="blue"> <input name="COLOR" id="Amarillo" type="radio" value="yellow"> <br> <input type="submit" value="Submit"> </form>
其他回答
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>
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)
这也是可行的,避免调用元素id,而是将其作为数组元素调用。
下面的代码是基于这样一个事实:一个名为radiobuttons组的数组是由radiobuttons元素组成的,它们的顺序与html文档中声明的相同:
if(!document.yourformname.yourradioname[0].checked
&& !document.yourformname.yourradioname[1].checked){
alert('is this working for all?');
return false;
}
您可以使用这个简单的脚本。 您可以有多个名称相同但值不同的单选按钮。
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.
}
我使用展开运算符和some来检查数组中至少有一个元素通过了测试。
我为谁分担关心。
var checked =[..文档.getElementsByName(“性别”).有些(c=>c.checked); 控制台日志(检查); <输入类型=“收音机”,性别“检查值=“男性”/> Male <输入类型=“无线电”