我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?
当前回答
对于jQuery,它就像这样
if ($('input[name=gender]:checked').length > 0) {
// do something here
}
让我把它分解成几部分,以便更清楚地解释。 jQuery从左到右处理事物。
input[name=gender]:checked
Input将其限制为输入标记。 [name=gender]将其限制为前一组中具有名称性别的标签。 :checked将其限制为前一组中选中的复选框/单选按钮。
如果您希望完全避免这种情况,可以在HTML代码中将其中一个单选按钮标记为已选中(checked="checked"),这将确保始终选中一个单选按钮。
其他回答
如果你想使用普通的JavaScript,不想在每个单选按钮上添加id而使你的标记变得混乱,并且只关心现代浏览器,那么下面的函数式方法对我来说比for循环更有品位:
<form id="myForm">
<label>Who will be left?
<label><input type="radio" name="output" value="knight" />Kurgan</label>
<label><input type="radio" name="output" value="highlander" checked />Connor</label>
</label>
</form>
<script>
function getSelectedRadioValue (formElement, radioName) {
return ([].slice.call(formElement[radioName]).filter(function (radio) {
return radio.checked;
}).pop() || {}).value;
}
var formEl = document.getElementById('myForm');
alert(
getSelectedRadioValue(formEl, 'output') // 'highlander'
)
</script>
如果两者都没有选中,它将返回undefined(尽管您可以更改上面的行以返回其他内容,例如,要得到false返回,您可以将上面的相关行更改为:}).pop() || {value:false}).value;)
还有一种前瞻性的polyfill方法,因为RadioNodeList接口应该可以很容易地在表单子无线电元素列表上使用value属性(在上面的代码中作为formElement[radioName]找到),但这也有它自己的问题:如何填充RadioNodeList?
http://www.somacon.com/p143.php/
function getCheckedValue(radioObj) {
if(!radioObj)
return "";
var radioLength = radioObj.length;
if(radioLength == undefined)
if(radioObj.checked)
return radioObj.value;
else
return "";
for(var i = 0; i < radioLength; i++) {
if(radioObj[i].checked) {
return radioObj[i].value;
}
}
return "";
}
HTML代码
<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >
Javascript代码:
var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
if(off_payment_method[i].checked) {
ischecked_method = true;
break;
}
}
if(!ischecked_method) { //payment method button is not checked
alert("Please choose Offline Payment Method");
}
表单
<form name="teenageMutant">
<input type="radio" name="ninjaTurtles"/>
</form>
这个脚本
if(!document.teenageMutant.ninjaTurtles.checked){
alert('get down');
}
小提琴:http://jsfiddle.net/PNpUS/
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)