CaptainCodeman
CaptainCodeman

Reputation: 2201

Javascript onkeypress event fires but input text value is incorrect

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>

Upvotes: 2

Views: 4951

Answers (2)

Tim Down
Tim Down

Reputation: 324537

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:

Upvotes: 1

Dor Cohen
Dor Cohen

Reputation: 17080

Change the event to onkeyup instead of onkeypress

inp.onkeyup=checkAnswer;

Upvotes: 6

Related Questions