Hello!
I’m trying to write some javascript code that will give a user one of two messages (Correct or incorrect) base on whether they answer a question correctly. I have 2 issues that I was hoping someone could help me with:
-
My “incorrect” and “correct” messages all appear on the page load. Is there anyway to start without them being there?
-
More troubling: No matter what I put into the input boxes, the “incorrect” message pops up. Basically I need to better understand how to grab the actual input value (it’s commented down below so I think that this should be a quick fix!)
Thanks so much,
Eric
function showAnswer(blurred,response)
{
var form = blurred.form;
var rbs = form[blurred.name];
for ( var r = 0; r < rbs.length; ++r )
{
var rb = rbs[r];
var lbl = rb.parentNode;
var ans = lbl.getElementsByTagName("span");
ans[0].style.display = ( (rb == blurred) && (response == "correct")) ? "inline" : "none";
ans[1].style.display = ( (rb == blurred) && (response == "incorrect")) ? "inline" : "none";
}
}
window.onload = function()
{
var answers = new Array("13","10.8","9.8"); ///my actual number of inputs is a lot longer, hence the array.
var inps = document.getElementsByTagName("input");
for ( var i = 0; i < inps.length; ++i )
{
inp = inps[i];
correct_answer = answers[i];
var response = "incorrect"; //Assume it's incorrect
if (inp == correct_answer) {response="correct";} //this SHOULD compare the input value to the correct response...help on this line please?
if ( inp.type == "text" ) inp.onblur = function() {
//Assume Correct
showAnswer(this,response);
}
}
}
<form>
<table><tr>
<td width="30" align="center">-2</td>
<td align="center"><label><input name="answer" type="text" size="3" maxlength="4" /><span> Correct!</span><span> Incorrect!</span></label></td>
</tr>
<tr>
<td width="30" align="center">-1</td>
<td align="center"><label><input name="answer" type="text" size="3" maxlength="4" /><span> Correct!</span><span> Incorrect!</span></label></td>
</tr>
<tr>
<td width="30" align="center">0</td>
<td align="center"><label><input name="answer" type="text" size="3" maxlength="4" /><span> Correct!</span><span> Incorrect!</span></label></td>
</tr></table?>
</form>