1

My if-else is not working, I think that I have a variable issue. When I look at the value of x it is not what is entered in the text field. Any Ideas?

function guess() {

    var x = document.getElementById("magic");

    var word = "please";
    if (x == word) {
        alert("You entered the magic word!");
    } else {
        alert("Please try again!");
    }
}

<form>
    What is the magic word?<br />
    <input type="text" id="magic" onchange="guess()" />
</form>
2
  • x = object, you will need to use .value in order to compare with word. Commented Sep 18, 2011 at 1:44
  • 1
    try var x = document.getElementById("magic").value Commented Sep 18, 2011 at 1:44

3 Answers 3

4

You're not getting the value. Use this:

var x =document.getElementById("magic").value;
Sign up to request clarification or add additional context in comments.

Comments

4

You want:

var x = document.getElementById("magic").value;

Also, onchange won't work, you'll need to use onkeyup, although onblur is probably more sane:

What is the magic word?<br />
<input type="text" id="magic" onblur="guess()" />

function guess() {
    var x = document.getElementById("magic").value;

    var word = "please";

    if (x == word) {
        alert("You entered the magic word!");
    } else {
        alert("Please try again!");
    }
}

http://jsfiddle.net/6uAhq/

2 Comments

Are you sure you'd want it to barrage the user with alerts? (onkey* would alert "Please try again!" for every letter they typed until they typed it all in correctly)
Yeah, onblur is probably better. I was thinking of the onchange, not the application.
2

You need to check against the actual value of the "magic" element, e.g.:

var x = document.getElementById("magic").value;

I'm assuming "magic" is an input.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.