Overcranked
Overcranked

Reputation: 175

Javascript if else problem

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>

Upvotes: 1

Views: 655

Answers (3)

Deep Frozen
Deep Frozen

Reputation: 2075

You're not getting the value. Use this:

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

Upvotes: 4

Jared Farrish
Jared Farrish

Reputation: 49238

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/

Upvotes: 4

Michael Irwin
Michael Irwin

Reputation: 3149

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.

Upvotes: 2

Related Questions