ferne97
ferne97

Reputation: 1073

Vue.js label for an input element inside loop

How would you set up the input id and the label for on repeated input elements so they are unique, using Vue.js v2.

<section class="section" v-for="(section, i) in sections">

    <div class="fields">
        <fieldset>
            <input type="checkbox" id="" name="example-a" v-model="section.ex-a">
            <label for="">Example A</label>
        </fieldset>
        <fieldset>
            <label for="">Example B</label>
            <input type="text" id="" name="example-b" v-model="section.ex-b">
        </fieldset>
        <fieldset>
            <label for="">Example C</label>
            <input type="text" id="" name="example-c" v-model="section.ex-c">
        </fieldset>
    </div>

</section>

I want to be able to click on the label element and have it select the input field.

Upvotes: 21

Views: 26029

Answers (1)

Daniel Orme&#241;o
Daniel Orme&#241;o

Reputation: 2778

You can use :id="" and :for="". You would need to add a js string interpolation to create a unique id from the section and index information. For example:

<div class="fields">
    <fieldset>
        <input type="checkbox" :id="'section'+i+'example-a'" name="example-a" v-model="section.ex-a">
        <label :for="'section'+i+'example-a'">Example A</label>
    </fieldset>
    <fieldset>
        <label for="'section'+i+'example-b'">Example B</label>
        <input type="text" :id="'section'+i+'example-b'" name="example-b" v-model="section.ex-b">
    </fieldset>
    <fieldset>
        <label :for="'section'+i+'example-c'">Example C</label>
        <input type="text" :id="'section'+i+'example-c'" name="example-c" v-model="section.ex-c">
    </fieldset>
</div>

For example, for the first fieldset the binding :id="'section'+i+'example-a'" will render id="section-0-example-a" as its interpolating 'section' + the index of the array + 'example-a'

Upvotes: 27

Related Questions