I currently have a form with two checkboxes corresponding to each question in which I'm trying to get all the values from all the checked checkboxes and store them into an "answers" array. I will then use this answers array in my POST request to store the answers in my database.
Although I'm having trouble achieving this, my form currently looks like this, with the options coming dynamically from my database.
<form class="quiz-form">
<div *ngFor="let option of quiz">
<label> {{option.question}}: </label>
<input type='checkbox' name='checkbox'/>
<label>{{option.choice1}} </label>
<input type='checkbox' name='checkbox'/>
<label>{{option.choice2}} </label>
</div
<button type="submit" value="Submit"> Complete quiz </button>
</form>
Can anyone help me achieve this? Thanks.
You can do something like below in your Template :
<form class="quiz-form">
<div *ngFor="let option of quiz">
<label> {{option.question}}: </label>
<input type='checkbox' name='{{option.choice1}}' value="{{option.choice1}}" (change)="selectAnswer(option, $event)"/>
<label>{{option.choice1}} </label>
<input type='checkbox' name='{{option.choice2}}' value="{{option.choice2}}" (change)="selectAnswer(option, $event)"/>
<label>{{option.choice2}} </label>
</div>
<button type="submit" value="Submit"> Complete quiz </button>
</form>
and in component file :
selectAnswer(category, event) {
var index = this.answer.indexOf(event.target.value);
if (event.target.checked) {
this.answer.push(event.target.value);
} else {
if (index !== -1) {
this.answer.splice(index, 1);
}
}
console.log(this.answer);
}
Here is the plunkr for the same.
EDIT
<form class="quiz-form" (ngSubmit)="submitForm()">
<div *ngFor="let option of quiz">
<label> {{option.question}}: </label>
<input type='checkbox' name='{{option.choice1}}' value="{{option.choice1}}" (change)="selectAnswer(option, $event)"/>
<label>{{option.choice1}} </label>
<input type='checkbox' name='{{option.choice2}}' value="{{option.choice2}}" (change)="selectAnswer(option, $event)"/>
<label>{{option.choice2}} </label>
</div>
<button type="submit" value="Submit"> Complete quiz </button>
</form>
and in component ts file :
submit(){
this.answer=[];
}