Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Radio button not staying checked when clicking another component

I have this parent component

Question

<template>
  <div class="question-container">
    <div class="question">
      <h2>{{ number }}. {{ question.question }}</h2>
      <Choice :choices="question.choices"/>
    </div>
  </div>
</template>

<script>
import Choice from "./Choice.vue";

export default {
  name: "Question",
  props: {
    question: String,
    number: Number,
  },
  components: {
    Choice,
  },
};
</script>

and this child component named

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Choice

<template>
  <div class="choice">
    <div v-for="(choice, index) in choices" v-bind:key="index">
      <label>
        <input type="radio" name="answer" />
        <span class="label-text">{{ choice }}</span>
      </label>
    </div>
  </div>
</template>

<script>
export default {
  name: "Choice",
  props: {
    choices: Array,
  },
};
</script>

The issue is that when you select a radio button on one component, then when you go to another component and try to select a radio button on the component. The radio button gets unselected from the other component. Multiple Question components are rendered and each of them has radio buttons. When you click a radio button on a Question component, all selected radio button gets unselected from the other components. Hope I made sense. How would I fix this?

>Solution :

Using the name= attribute on a radio button is what HTML uses to group it with other radios for the same input. You’ll need this to be unique per question.

The questions already have a number prop (which I hope is some sort of ID? If not, you could add an id attribute to each)

I would pass this to the choices:

<Choice :choices="question.choices" :id="number"/> 

Then render it in the Choice:

<template>
  <div class="choice">
    <div v-for="(choice, index) in choices" v-bind:key="index">
      <label>
        <input type="radio" :name="`answer-${id}`" />
        <span class="label-text">{{ choice }}</span>
      </label>
    </div>
  </div>
</template>

<script>
export default {
  name: "Choice",
  props: {
    choices: Array,
    id: Number
  },
};
</script>

This renders

<input type="radio" name="answer-1" />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading