我真的需要立即使用javascript。
我在xhtml中创建了一个mcq测验,并尝试使用javascript进行验证。问题是,如果任何问题没有得到答复,我可以显示警告信息。但我想在同一个警报信息中列出未答复的问题编号。请参阅以下代码。
需要立即解决方案。非常感谢提前。
<script type="text/javascript">
<!--
function validateRadio(radio) {
var retval = false
for ( var i = 0; i < radio.length; i++ ) {
if ( radio[i].checked ) retval = true;
}
return retval;
}
// to make sure all questions are answered
function validateForm(theForm) // to make sure all questions are answered
{
var retval = true;
if ( !validateRadio(theForm.q1) ) retval = false;
if ( !validateRadio(theForm.q2) ) retval = false;
if ( !validateRadio(theForm.q3) ) retval = false;
if ( !retval ) alert("Answer all of the questions");
return retval;
}
// --></script>
<form name="quiz" action="result.php" method="post">
<p>1. Choose the correct set of solution(s) by solving <img src="images/image002.png" width="93" height="17" alt=""/> equation?<br/>
<input type="radio" name="q1" value="1"/>gh<br/>
<input type="radio" name="q1" value="2"/>hk<br/>
<input type="radio" name="q1" value="3"/>h<br/>
<input type="radio" name="q1" value="4"/>ncb</p>
<p>2. What is the value of <i>x</i> when 78x ?<br/>
<input type="radio" name="q2" value="1"/>90<br/>
<input type="radio" name="q2" value="2"/>656<br/>
<input type="radio" name="q2" value="3"/>2<br/>
<input type="radio" name="q2" value="4"/>5</p>
<p>3. What is the value of 5x ?<br/>
<input type="radio" name="q3" value="1"/>+3<br/>
<input type="radio" name="q3" value="2"/>+6<br/>
<input type="radio" name="q3" value="3"/>-3<br/>
<input type="radio" name="q3" value="4"/>-6</p>
<p><input type="submit" name="submit" value="Submit Now!" onclick="return validateForm(this.form)"/></p>
答案 0 :(得分:0)
这样做:
function validateForm(theForm) // to make sure all questions are answered
{
var retval = true;
var unanswered = "";
if ( !validateRadio(theForm.q1) ){retval = false;unanswered += "Question1\n";}
if ( !validateRadio(theForm.q2) ){retval = false;unanswered += "Question2\n";}
if ( !validateRadio(theForm.q3) ){retval = false;unanswered += "Question3\n";}
if ( !retval ) alert("Answer all of the questions\nThe following were unanswered:\n" + unanswered);
return retval;
}