How to make an html form start a function

大憨熊 提交于 2019-12-13 04:03:46

问题


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>

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/22213632/how-to-make-an-html-form-start-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!