使用Javascript验证单选按钮 [英] Validation of radio buttons with Javascript
本文介绍了使用Javascript验证单选按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经在这里梳理了大量的页面,但仍然无法让我的显式验证器工作。基本上,当单击提交按钮时,我希望脚本验证是否检查了无线电,如果检查了无线电。如果没有选中,我希望它发布一条警告信息。
I've combed a ton of the pages on here, and still am incapable to get my explicit validator to work. Basically, when the submit button is clicked, I want the script to verify a radio is checked, if one is checked to do nothing. If one isn't checked I want it to post an alert message.
大致上我的html看起来像:
roughly my html looks like:
<form id="myForm" onsubmit = "check()">
<input type = "radio" name = "c" id = "1" value = "1" />
<input type = "radio" name = "c" id = "2" value = "2" />
<input type = "radio" name = "c" id = "3" value = "3" />
<input type = "submit" value = "Submit" />
我的JS页面如下:
my JS page looks like:
function check() {
var r = document.getElementsByName("c")
var c = 0
for(var i=0; i < r.length; i++){
if(c[i].checked) {
c = i; }
}
alert("please select radio");
}
推荐答案
试试这个
function check() {
var r = document.getElementsByName("c")
var c = -1
for(var i=0; i < r.length; i++){
if(r[i].checked) {
c = i;
}
}
if (c == -1) alert("please select radio");
}
这篇关于使用Javascript验证单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文