2

I'm writing a simple javascript form that checks the input value against the value "blue". Now if you enter "blue", it says it's incorrect, but then if add any additional character, it says correct. It seems like there's a one-character delay, so when I enter "blue" it's only getting "blu". Here is the code:

<html>
<head>
<title>Favorite Color</title>
</head>

<body>
<h1>Quiz Time</h1>
<h2>What is your favorite color?</h2>

<p>Your Answer: <input type="text" id="txtinput" /></p>
<p id="message"></p>

<script type = "text/javascript">
function init() {
    var inp = document.getElementById("txtinput");
    inp.onkeypress=checkAnswer;

    checkAnswer();
}

onload = init;

function checkAnswer() {
    var text = document.getElementById("txtinput");
    var msg = document.getElementById("message");

    var sol = "blue";
    var ans = text.value;
    ans = ans.toLowerCase();

    if (ans.length <=0) {
        msg.innerHTML="<span style=\"color:blue;\">Enter Something.</span>";
    }
    else if (ans == sol) {
        msg.innerHTML="<span style=\"color:green;\">Correct!</span>";
    } else {
        msg.innerHTML="<span style=\"color:red;\">Wrong!</span>";
    }
}

</script>
</body>
</html>
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
CaptainCodeman
  • 1,951
  • 2
  • 20
  • 33

2 Answers2

6

Change the event to onkeyup instead of onkeypress

inp.onkeyup=checkAnswer;
Dor Cohen
  • 16,769
  • 23
  • 93
  • 161
1

Use the HTML5 input event with a fallback to the propertychange event in IE < 9. I've written about this many times on SO; here are two examples:

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536