0

I'm working on a quiz app and want to generate a number of input fields representing the answers based on the value that the user types. I'm using a button named "create" to do that Using JavaScript, but when clicking the button it submits the form.

Please Check the two images below.

Input

Output

HTML Code

{% load static %}

{% block body %}

<button class="btn btn-primary new">Add a question</button>

<form class="question" method="POST" style="display: none">
    {% csrf_token %}
    <div class="form-group">
        <label for="exampleInputEmail1">Title</label>
        <input type="text" class="form-control" id="title" placeholder="Question title">
    </div>
    <div class="form-group" id="answers_num">
        <label for="exampleInputPassword1">Number of answers</label>
        <input type="number" class="form-control" id="ans_number">
        <button class="create_answers">Create</button>
    </div>

    <div class="form-group">
        {% comment %} Generated input fields {% endcomment %}

    </div>

    <button type="submit" class="btn btn-primary">Submit</button>
</form>



{% block script %}
    <script src="{% static 'mcq/index.js' %}"></script>
{% endblock %}

{% endblock %}```

JS code

document.querySelector(".new").addEventListener("click", ()=> {

    document.querySelector(".question").style.display = 'block';

    document.querySelector("#create_answers").addEventListener("click", ()=> {
        answers = this.value;

        console.log(answers);

        // Create input fields
        for (let i = 0; i < answers; i++) {
            input = document.createElement("input");
            input.classList.add('form-control');
            answersDiv = document.querySelector("#answers").appendChild(input);
        }

    })
})```

1 Answer 1

2

You need to explicitly set the type of the button, like

<button class="create_answers" type="button">Create</button>

in order to avoid submitting the form upon click.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.