我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?
当前回答
只是试图改进Russ Cam的解决方案与一些CSS选择器糖扔在香草JavaScript。
var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;
这里不需要jQuery, querySelectorAll现在已经得到了足够广泛的支持。
编辑:修正了一个css选择器的错误,我已经包括了引号,虽然你可以省略它们,在某些情况下你不能这样做,所以最好把它们留在。
其他回答
有一种非常复杂的方法可以用ECMA6和.some()方法验证是否选中了任意单选按钮。
Html:
<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />
和javascript:
let htmlNodes = document.getElementsByName('status');
let radioButtonsArray = Array.from(htmlNodes);
let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);
如果选中了一些单选按钮,isAnyRadioButtonChecked将为真,如果两个单选按钮都没有选中,则为假。
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)
只是试图改进Russ Cam的解决方案与一些CSS选择器糖扔在香草JavaScript。
var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;
这里不需要jQuery, querySelectorAll现在已经得到了足够广泛的支持。
编辑:修正了一个css选择器的错误,我已经包括了引号,虽然你可以省略它们,在某些情况下你不能这样做,所以最好把它们留在。
一种简单的JavaScript方式
var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio' && radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
}
}
给单选按钮,相同的名称,但不同的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;
}
}