I have a web page that includes a quiz. I’m using javascript for validation. I did it a long time ago but now I want to update it and I’m pulling my hair out.
I have 868 lines of javascript and I KNOW it can be done with less than 12 lines.
Here’s a very short snippet. There’s actually 72 questions total.
[CODE]
<script type=”text/javascript”>
var answer1=”dead poets society”
var answer2=”unforgiven”
function validate1(quiz){
if (quiz.movie1.value == answer1)
{
quiz.movie1.style.backgroundColor=(‘#00FF00’); //Green
quiz.focus();
}
else if (quiz.movie1.value != answer1)
{
quiz.movie1.style.backgroundColor=(‘#FF3300’); //Red
quiz.focus();
}}
function validate2(quiz){
if (quiz.movie2.value == answer2)
{
quiz.movie2.style.backgroundColor=(‘#00FF00’); //Green
quiz.focus();
}
else if (quiz.movie2.value != answer2)
{
quiz.movie2.style.backgroundColor=(‘#FF3300’); //Red
quiz.focus();
}}
Here’s the html.
[CODE]
<td><div align=”center”><img src=”1.jpg” width=”275″ height=”155″><br>
1. <input type=”text” name=”movie1″ onBlur=”this.value=this.value.toLowerCase(); validate1(quiz)”>
</div><p> </p></td>
<td><div align=”center”><img src=”2.jpg” width=”275″ height=”155″><br>
2. <input type=”text” name=”movie2″ onBlur=”this.value=this.value.toLowerCase(); validate2(quiz)”>
</div><p> </p></td>
I tried calling the function by using validate(1); the using
function validate(nmbr) and it seem to work but I can’t figure out how to assign and call a variable for the form field name to change the background.
Here’s as far as I could get.
[CODE]
answer = new Array(“placeholder”,”dead poets society”)
function validate(nmbr){
if (quiz.movie1.value == answer[nmbr])
{
quiz.movie1.style.backgroundColor=(‘#00FF00’); //Green
quiz.focus();
}
else if (quiz.movie1.value != answer[nmbr])
{
quiz.movie.style.backgroundColor=(‘#FF3300’); //Red
quiz.focus();
}}