Submit multiple forms with one button in pug

Viewed 31

I'm currently making a quiz application that dynamically serves a user a list of questions with a dropdown to select their answer from using:

    ul
        each val in questions
            li
                div
                    label= val.Question
                    form(method='POST')
                        select(name='questionAnswer')
                            option(value='true') True
                            option(value='false') False

                    button(type="submit") Submit
                

I'm attempting to push these answers into an array to later use for comparing to their correct answer.

let radioAnswers = [];

router.post('/play', function(req, res) { 
  answers.push(req.body.radio)
  console.log(radioAnswers)
})

However it's not too functional having a submit button next to every question, that can be easily broken. How would I go about having one submit button to submit every form?

1 Answers

Put everything in one form and give each question its own name for the input’s name attribute.

form(method='POST')
    ul
        each val in questions
            li
                div
                    label= val.Question
                        select(name=val.Name)
                            option(value='true') True
                            option(value='false') False

    button Submit

Then you use req.body[val.Name] to retrieve the answer for each question on the server.

Related