我一直在努力让javascript验证一个使用单选按钮的基于WordPress的超文本标记语言表单。我最终想出了一个解决方案,虽然有点冗长,但至少在IE和Chrome中有效,但在Firefox中不起作用(这表明我的代码有点马虎)。我想问题出在我的单选按钮引用上。除了使用一种低效的验证方法:-)之外,有人可以帮助我做错的事情吗?
我的表单的简化版本:
<script>
function validateForm()
{
var aa=document.forms["personalise"]["motivation"]["1a"];
var ab=document.forms["personalise"]["motivation"]["1b"];
var ac=document.forms["personalise"]["motivation"]["1c"];
var ad=document.forms["personalise"]["motivation"]["1d"];
var ae=document.forms["personalise"]["motivation"]["1e"];
if (!(aa.checked == true || ab.checked == true || ac.checked == true || ad.checked == true || ae.checked == true))
{
alert("Question 1 must be completed");
return false;
}
}
</script>
<form name="personalise" action="insertdatatest.php" onsubmit="return validateForm()" method="post">
1. Are you seriously planning to quit </b>:
<input id="1a" type="Radio" title="" name="motivation" value="1" /> Within the next 2 weeks
<input id="1b" type="Radio" title="" name="motivation" value="2" /> Within the next 30 days
<input id="1c" type="Radio" title="" name="motivation" value="3" /> Within the next 3 months
<input id="1d" type="Radio" title="" name="motivation" value="4" /> No, I am not currently planning to quit
<input id="1e" type="Radio" title="" name="motivation" value="5" /> I have already quit
<input type="submit" value = "Submit">
</form>我是一个真正的新手在网络开发,所以任何帮助都会非常感谢。
发布于 2012-10-22 23:16:31
再次感谢TheDeadMedic的帮助。实际上,我发现了一种略微不同的方法,它在所有三种浏览器中都有效,它是为多个单选按钮问题设置的(因此有blOK条目)。如果它对任何其他人有用,代码如下。弗利克斯。
<script>
function validateForm() {
var inputs;
var i;
var blOK;
blOK = false;
inputs = document.getElementsByName( "motivation" );
for (i=0;i<inputs.length;i++)
{
if ( inputs[i].checked ) {
blOK = true ;
break ;
}
}
if (!blOK)
{
alert( "Question 1 must be completed" );
return false;
}
</script>发布于 2012-10-20 17:58:56
这里有一种更干净的做事方式:
function validateForm() {
var inputs = document.getElementsByName( "motivation" );
for ( var i = 0; i < inputs.length; i++ ) {
if ( inputs[i].checked ) return true;
}
alert( "Question 1 must be completed" );
return false;
}https://stackoverflow.com/questions/12987183
复制相似问题