我的代码有什么问题?我需要验证一个单选按钮。它工作正常,直到最后一项。选择是或否后,我可以提交最后一个选项为空的表单。我似乎无法验证最后一个选项。我也没有写这个脚本。老实说,我不明白它是如何工作的:/
这就是我所拥有的
function valida () {
if (document.example.name.value=="") {
alert ('NAME field is empty!');
return false;
}
else if (document.example.email.value=="") {
alert ('EMAIL field is empty!');
return false;
}
var radios = document.getElementsByName("yesorno");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select Yes or No!");
return formValid;
var radios = document.getElementsByName("color");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Pick a colour!");
return formValid;
else {
return true;
}
}
<form name="example" id="example" action="submit-form.php" method="post" onsubmit="return valida();">
<fieldset>
<label for="name">Name:</label>
<input type="text" name="name" id="name"/>
<label for="email">Email:</label>
<input type="text" name="email" id="email"/>
<label>Yes or No?</label>
YES
<input name="yesorno" type="radio" class="radio" value="yes" />
NO
<input name="yesorno" type="radio" class="radio" value="yes" />
<label>Red, green or yellow?</label>
red
<input name="color" type="radio" class="radio" value="red" />
green
<input name="color" type="radio" class="radio" value="green" />
yellow
<input name="color" type="radio" class="radio" value="yellow" />
<input type="submit" value="submit" />
</fieldset>
</form>
编辑:我在stackoverflow上找到了一个解决方案。这现在对我有用:
function valida () {
if (document.example.name.value=="") {
alert ('NAME field is empty!');
return false;
}
else if (document.example.email.value=="") {
alert ('EMAIL field is empty!');
return false;
}
else if ($('input[name=yesorno]:checked').length == 0) {
alert ('Select Yes or No!');
return false;
}
else if ($('input[name=color]:checked').length == 0) {
alert ('Pick a colour!');
return false;
}
else {
return true;
}
}