-1

When I type in an ID number for the game, I always gets the 3rd statement of my if else expression. Where am I going wrong?!!

<html>
<body>
<p>Type in the ID and hit search:</p>
<button onclick="myFunction()">Search</button>
<p id="demo"></p>
    <form>
        <input id="textbox" type="text" />
    </form>
<script>
var textboxValue = document.getElementById("textbox").value;
function myFunction() {
    var message;
    if (textboxValue == 1) {
        message = "Fantasy World";
    } else if (textboxValue == 2) {
        message = "Sir Wags A Lot";
    } else {
        message = "Take a Path";
    }
document.getElementById("demo").innerHTML = message;
}
</script>
</body>
</html>

2 Answers 2

8

The problem is you always test the same, initial, value of the input.

Change

var textboxValue = document.getElementById("textbox").value;
function myFunction() {

to

function myFunction() {
    var textboxValue = document.getElementById("textbox").value;

This way the value will be read each time the function is called.

Sign up to request clarification or add additional context in comments.

2 Comments

Can the downvoter explain the problem in my answer ?
@dystroy Thank you dystroy. That's really helpful. People like you help newbies like me to improve and I am extremely grateful
4

Put this statement:

var textboxValue = document.getElementById("textbox").value;

Inside the function.

1 Comment

I edited your answer to change the code formatting from a quote (you get this with ctrl-Q) to a code bloc (you get that with Ctrl-K).

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.