我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?
当前回答
这也是可行的,避免调用元素id,而是将其作为数组元素调用。
下面的代码是基于这样一个事实:一个名为radiobuttons组的数组是由radiobuttons元素组成的,它们的顺序与html文档中声明的相同:
if(!document.yourformname.yourradioname[0].checked
&& !document.yourformname.yourradioname[1].checked){
alert('is this working for all?');
return false;
}
其他回答
使用JQuery,另一种检查单选按钮当前状态的方法是获取属性“checked”。
例如:
<input type="radio" name="gender_male" value="Male" />
<input type="radio" name="gender_female" value="Female" />
在这种情况下,你可以检查按钮使用:
if ($("#gender_male").attr("checked") == true) {
...
}
我使用展开运算符和some来检查数组中至少有一个元素通过了测试。
我为谁分担关心。
var checked =[..文档.getElementsByName(“性别”).有些(c=>c.checked); 控制台日志(检查); <输入类型=“收音机”,性别“检查值=“男性”/> Male <输入类型=“无线电”
如果你想使用普通的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?
返回单选按钮中所有选中的元素
Array.from(document.getElementsByClassName("className")).filter(x=>x['checked']);
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;
}