<form>
<input id="gen" name="gender" type="radio"> Male
<br>
<input id="gen1" name="gender" type="radio"> Female
</form>
function formValidate() {
if((gen.checked==false)&&(gen1.checked==false)) {
alert("please select a gender");
return false;
}
}
答案 0 :(得分:1)
您可以尝试通过以下方式检查checked
属性:
function formValidate(e) {
var chkEl = document.querySelector('[name=gender]:checked');
if(chkEl == null){
alert("please select a gender");
e.preventDefault();
}
}
<form>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<button onclick="formValidate(event)">Click</button>
<form>
答案 1 :(得分:0)
<form onsubmit="return formValidate()">
<input id="gen" name="gender" type="radio"> Male
<br>
<input id="gen1" name="gender" type="radio"> Female
</form>
function formValidate() {
if((gen.checked==false)&&(gen1.checked==false)) {
alert("please select a gender");
return false;
}
}
您需要在提交函数时调用函数,然后才能进行验证。您可以使用jQuery单击“函数”来验证字段。
答案 2 :(得分:0)
您可以设置onsubmit="return formValidate()"
属性,当客户端单击“提交”按钮时将调用该属性
function formValidate() {
if((gen.checked==false)&&(gen1.checked==false)) {
alert("please select a gender");
return false;
}
else
return true;
}
<form onsubmit="return formValidate()">
<input id="gen" name="gender" type="radio"> Male
<br/>
<input id="gen1" name="gender" type="radio"> Female
<br/>
<input type="submit" value="Submit">
</form>