Reputation: 17
I have the following scenario. I get a list of Questions
from my backend and each Question
contains the following properties:
Now, I'm rendering the questions with v-for
and displaying them as a form with the Statement
as a simple <p>
and the choices
are a set of checkboxes (rendered also with v-for
).
Question Statement 1
[x] choice1
[] choice2
[x] choice3
--------------------
Question Statement 2
[x] choice1
[x] choice2
[] choice3
--------------------
Question Statement 3
[x] choice1
[] choice2
[] choice3
--------------------
I know how to bind a set of checkboxes to a given property, but here I don't have a single set of checkboxes, but multiple, depending on the number of questions fetched from the backend. I want in the end to submit the form and send an HTTP POST request to the backend with the answers given (something like the following):
[
{
"questionId": 1,
"selectedAnswers": [choice1, choice3]
},
{
"questionId": 2,
"selectedAnswers": [choice1, choice2]
},
{
"questionId": 3,
"selectedAnswers": [choice1]
}
]
My problem is that I cannot find a way to bind all the selected choices. If I select and array and bind them in the input
with v-model
the last checkbox that I will select will override everything. I need to somehow bind the array of selected choices alongside the questionId so everything will unique.
Do you have any clues on this?
Many thanks!
Upvotes: 0
Views: 177
Reputation: 1111
Create an object from the items that come from your backend after fetching them:
// presuming the variable holding your backend data is called `data`
let questions = [...data]
for (let question of questions) {
question['selectedChoices'] = []
}
Now render your questions with the questions array, and bind the checkboxes in each question to the selectedChoices
array.
Upvotes: 2