Running a function when form submitted

Running a function when form submitted
0

#1

I’m doing a project where the user will be presented with a number of arithmetic problems. They will have to answer as many questions as possible in the time given.

I am struggling with getting the form to work as desired. I want the user to be able to enter the value for the answer, hit enter, and the next problem will be shown. Behind the scenes when the user submits their answer a function will run which will validate the answer right or wrong. (I haven’t created these functions yet, I just want to get a test one to run first before I go further with that)

I have the following html:

<form id="getAnswer" autocomplete="off" accept-charset="utf-8" onsubmit="test()">
                <input type="text" id="answer" name="answer">
                <input type="submit" value="Submit Answer">
                </form>

And JS:

    function test() {
        var userAnswer = $("#answer")[0].value;
        console.log(userAnswer);
    }
    $("#test").click(function () {
        test();
    });

If you click my test button the test function runs, easy enough. When you submit the form in the console you get the error: “TypeError: Test is not a function” Why is this, and how could I get function to run when the form is submitted?

Is the method I used to get the value of the user’s answer in the userAnswer var a good way to go about it, or is there a smarter way to do this?


#2
  1. In jquery you can do like this
    $("#getAnswer").submit(function(e) {
    e.preventDefault();
    test();
    });

After this there is no need to pass onSubmit attribute on form

2)It’s fine


#3

Brilliant, that works perfectly for me. Thanks!