简体   繁体   中英

How can I create a dynamic form?

I'm trying to build an interactive Form with Flask. Specifically, its a form made for teachers to make a quiz. Every question has multiple answers. Everything needs to be done dynamically since every question may have a different number of answers, and each quiz may have a different number of questions.

When the user clicks on a button, a new input field gets added with Javascript. Each field is a new <input type="text" required> . Here's a sample of the HTML. Everything in the <div with id="quiz" is being dinamically generated with javascript and some buttons.

<form method="post">
    <div class="form-group">
        <label for="course">Select the course</label>
        <select class="form-control" name="course" id="course" required="">

            <option value="1">Course 1</option>

            <option value="2">Course 2 </option>

        </select>

        <div class="quiz" id="quiz">

            <div class="question">
                <input type="text" id="1" required>
                <div class="answer">
                    <input type="text" id="4" required>
                    <label>Correct?</label>
                    <input type="checkbox">
                </div>
                <div class="answer">
                    <input type="text" id="6" required>
                    <label>Correct?</label>
                    <input type="checkbox">
                </div>
                <div class="answer">
                    <input type="text" id="8" required>
                    <label>Correct?</label>
                    <input type="checkbox">
               </div>
            </div>

        </div>

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

Expected behaviour

With Flask, I should be able to do something like this and get all the fields that have been added

@dashboard.route('/newQuiz', methods=['POST', 'GET'])
def newQuiz():
    if request.method == 'POST':
        print(request.form) #immutableMultiDict with all the data

What Happens request.form only returns the course selection. The course is the only thing that is being generated in Python. Every other input that has been added with JS is NOT present in the POST request.

How can I add this dynamic content into the POST request?

Here to give an answer for my own question, since I figured out that the behaviour I was looking for is "not a thing" in Flask. I had to manually get everything in the form with Javascript, make a AJAX request to the server and refresh the page.

fetch(`${window.location}`, {
        method: "POST",
        body: JSON.stringify(quiz), //this should be your object
        cache: "no-cache",
        headers: new Headers({
            "content-type": "application/json"
        })
    }) //getting the response back
        .then(function (response) {
            if (response.status !== 200) {
                console.log(`Response status was ${response.status}`)
                return;
            }

            response.json().then(function (data) {
                console.log(data);
                location.reload(); // this is needed if you want to flash messages!
            })
        })

and then, with python

@yourBlueprint.route('/', methods=['GET','POST'])
def something():
    if request.method == 'POST':
        quiz = request.get_json() # this is now a dictionary, do whatever you want with it!
        flash("Okie dokie, i've received your stuff") 
        return make_response(jsonify({'message': 'hello from the other side'}), 200)

Hope this helps someone in the future!

EDIT I was wrong. The method above works, but it was a big oopsie on my end. input tags NEED a name attribute in order to be accessible in the ImmutableMultiDict Object. To sum it up, the code in the initial post works, but you need to add a name attribute in every input tag.

<div class="answer">
  <input type="text" id="4" name="text1" required>
  <label>Correct?</label>
  <input type="checkbox" name="checkbox1">
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM