Skip to content Skip to sidebar Skip to footer

How To Make An Html Form Start A Function

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, c

Solution 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


Solution 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.


Post a Comment for "How To Make An Html Form Start A Function"