Pergunta

I'm wondering if there is an easy way to make a form button with text input start a form that will check if the answer's correct and then proceed to tell you. Here's what I have, can you tell me what I need?

<!doctype html>
<body>
 <center>
  <form name="Input" action="Answer" method="get">
   <input type="text" name="Input">
   <input type="submit" value="submit">
  </form>
  <script type="text/javascript">
   var A = Math.floor(Math.random()*11);
   var B = Math.floor(Math.random()*11);
   var C = A+B;
   var Input = document.getElementById('Input');
   document.write(A + "+" + B)
   function Answer()
   {
     alert("correct!!");
   }
 </script>

</body>
</html>
Foi útil?

Solução

function calculateAnswer()
{
var A = Math.floor(Math.random()*11);
var B = Math.floor(Math.random()*11);
var C = A+B;
var Input = document.getElementById('Input');
if(Input.value == C)
{
document.body.innerHTML += (A + "+" + B);
//  Or another thing to do if the answer's correct
}
}

Also, attach an event listener to the submit button to make it run the function:

referenceToTheSubmitButton.addEventListener("click", calculateAnswer);

Indent as needed. Enjoy! :D

Outras dicas

I know you aren't using jQuery, but are you looking for something of this nature?

It can easily be changed to plain javascript. I just wanted to use bootstrap for the easy visual effect of the alerts.

The html would be something along these lines (with jQuery and bootstrap):

<div class="alert alert-danger" id="correct">Your answer is currently 
    <span id="type"> INCORRECT </span>
</div>
<form>
    <input name="answer" id="answer">
</form>
<p>Hint: the answer is "correct"</p>

and the script would work like this:

$("#answer").keyup(function(){
if($(this).val() === "correct"){
    $("#correct").removeClass("alert-danger")
    .addClass("alert-success");
    $("#type").text("CORRECT!")
}
else{
    $("#correct").removeClass("alert-success")
    .addClass("alert-danger");
    $("#type").text("INCORRECT!")
}
}).keyup();

This is just a basic implementation of an input that checks for an answer. In this case, typing "correct" makes the alert green.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top