JS - Check if the input field equals the solution

2019-02-28 21:07发布

I'm making a simple website for little kids with mathproblems,

the page contains a number of questions that the kids need to solve. They can press on 1 button that checks if the value that they inputted, equal is to the solution. JAVASCRIPT is obligated

I have this in HTML:

Question 1: how much is 8 x 4? 
<br><input type="text"> <br>
<button onclick="question1()">Check if your answer is correct?</button> 

my function already has this, but i can't seem to make up my mind with the syntax that looks correct:

function question1() {
  if (value == 32) {
     window.alert("correct!");
  } else {
     window.alert("try again);
  }
}

but my syntax looks correct?

3条回答
来,给爷笑一个
2楼-- · 2019-02-28 21:42

You have to give an input box an unique ID. Then, you can obtain its value like this:

var value = document.getElementById("your-id").value;

Full code: http://jsfiddle.net/7uwNn/

Good luck with your project!

查看更多
走好不送
3楼-- · 2019-02-28 21:54

window.alert("try again); needs to be window.alert("try again"); You forgot to place a quote

查看更多
冷血范
4楼-- · 2019-02-28 21:56

Took me a minute to realise you had simply not completed your quotes on the window alert "try again"

function question1() {
  if (value == 32) {
     window.alert("Correct!");
   } else {
      window.alert("Try again")
   }
}
查看更多
登录 后发表回答