Skip to content
Advertisement

How do I write html for form with multiple questions that use radio input type?

I have this quiz in multiple choice format where users can select one option per question and submit their answers at the end. This example shows what I’m trying achieve: [Example code w3school][1]

The problem I’m having is that selecting an option on a question de-selects any previous selection, meaning only one option can be selected for the entire quiz.

This is a section of my form template:

<form @submit.prevent="submit">
<div v-for="question in questions" :key="question.id">
 <jet-label :for="question.question" :value="question.question" class="font-bold text-lg" />
     <div v-for="option in question.options" :key="option.id">
        <jet-label :for="option.option" :value="option.option" />
        <input :id="option.id" type="radio" :value="option.option" 
        :name="option.question_id" v-model="form.options" />
     </div>
</div>
<div class="flex items-center justify-end mt-4">
    <jet-button class="ml-4" :class="{ 'opacity-25': form.processing }" 
     :disabled="form.processing">
       Submit
     </jet-button>
</div>
</form>

And this is the JS to handle user selection binding:

<script setup>
...
import { useForm } from '@inertiajs/inertia-vue3'

defineProps({
    questions: Array
})

const form = useForm({
    options: []
})

...
</script>

The issue probably is that inputs are seen as belonging to one group. How can I group the inputs based on the question id so that the select/deselect radio action is per question? [1]: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_input_type_radio

Advertisement

Answer

v-model="form.options" seems to be the problem, all inputs have the same model. Everytime a radio is selected it overwrites the this.options with the option value.

Try:

v-model="form.options[option.question_id]"

if that dosen’t work try to add a custom event handler with @change

BTW: option.question_id is a weird data structure it meight be better to have the id in the question object, because it seems the options lay in an array inside the question object

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement