Skip to content
Advertisement

OnSubmit function not working for an input type= ‘submit’

I am making a quiz app using django and it’s my first ever work using django Everything else is working fine instead of one thing which is whenever i press the button to submit the answer, page simply reloads.

Here’s my html code:

<section>
    <div id = "results"></div>
        <form name = "quizForm" onsubmit = "return submitAnswers(answers = [{% for q in questions%}'{{ q.answer }}',{% endfor %}])">
                {% for q in questions %}
                    <h3> {{ q.id }}.  {{ q.question }}</h3>
                    ..........
                {% endfor %}
                <input type = "submit" value = "Submit Answer">
            </form>
            <br><br>
        </section>

Here’s the js code relevance to the button:

function submitAnswers(answers) {

    var total = answers.length;
    var score = 0;
    var choice = []

    //dynamic method to get selected option
    for (var i = 1; i <= total; i++) {
        choice[i] = document.forms["quizForm"]["q" + i].value;
    }

    //dynamic method 1 for checking answer
    for (i = 1; i <= total; i++) {
        if (choice[i] == answers[i - 1]) {
            score++;
        }
    }

    //Display Result
    var results = document.getElementById('results');
    results.innerHTML = "<h3>You scored <span>" + score + "</span> out of <span>" + total + "</span></h3>"
    alert("You scored " + score + " out of " + total);

    return false;
}

According to this script I must see an alert whenever i press the submit button but the page simply reload without showing any alert messages. I am new in working with django apps if there is something I’m missing please guide. ThankYou!

Advertisement

Answer

I think that you need to remove the action on the form as the form is required to submit it back to the server. And add the event to the input. There’s also a div missing. I don’t know what the pre-processing does, so I have just copied it. Something like

<section>
    <div id = "results"></div>
        <form name = "quizForm">
                {% for q in questions %}
                    <h3> {{ q.id }}.  {{ q.question }}</h3>
                    ..........
                {% endfor %}
                <input type = "button" value = "Submit Answer"
                 oninput = "return submitAnswers(answers = [{% for q in questions%}'{{ q.answer }}',{% endfor %}])">
        </form>
        <br><br>
   </div>
</section>
...
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement