我的代码出了什么问题?我需要验证一个单选按钮。 它工作正常,直到最后一项。选择是或否后,我将提交表格,最后一个选项为空。我似乎无法验证最后一个选项。 我也没有写这个剧本。老实说,我不明白它是如何工作的:/
这就是我所拥有的
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;
}
}
答案 0 :(得分:0)
在返回其余代码之前,您将返回“是/否”验证。如果返回包含在if语句中,则将到达其余代码。试试这个:
<script language=javascript>
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;
}
radios = document.getElementsByName("color");
formValid = false;
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;
}
}
名称: 电子邮件: 是还是不是? 是 没有 红色,绿色还是黄色? 红色 绿色 黄色