Vue3: Programmatic radio check and name binding

Hi,

Sorry to ask such a dumb question but I have this:

<div class="form-check text-start" v-for="(el,idx) in melements" :id="'str' + idx">
            <input class="form-check-input p-2" :name="id" type="radio" @change="$emit('value', idx)" />
            <label class="form-check-label w-100" for="id">
</div>

And I would like the for=“id” to follow the “:id”. I succeeded for the name but the for… using “:for” didn’t make it.

Complementary question: I would like the input to be checked when I click on the label as well, but I don’t remember the best composition syntax. Could you refresh my memory?

Thanks a lot guys,

hi @glad
This code works like this, if you click on the label then also radio button checked

<template>
  <input type="radio" id="one" value="One" v-model="picked" />
  <label for="one">One</label>
  <br />
  <input type="radio" id="two" value="Two" v-model="picked" />
  <label for="two">Two</label>
  <br />
  <span>Picked: {{ picked }}</span>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      picked: "",
    };
  },
};
</script>

For a working example click on this link: RadioButtonDemo

Sure, thanks,
but the id of the input is a dynamically generated one, and this is where I don’t know how to reference it :slight_smile:

@glad I have worked on your problem that you want the id of the input to be a dynamically generated one.
Check out below source code.

<template>
  <ul>
    <li v-for="item in melements" :key="item.id">
      <input type="radio" :id="item.id" name="item.id" />
      <label :for="item.id">{{ item.name }}</label>
    </li>
  </ul>
</template>

<script>
export default {
  name: "App",
  components: {},
  data() {
    return {
      melements: [
        { id: "one", name: "one" },
        { id: "two", name: "two" },
      ],
    };
  },
};
</script>

For a working example click on this link: Dynamic Binding
Hope this works

Thanks a lot,

My mistake was to bind the name as well. Your succeeding example is very welcome :+1:

1 Like