Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js label for an input element inside loop

Tags:

vue.js

vuejs2

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.

like image 639
ferne97 Avatar asked Jun 20 '17 22:06

ferne97


1 Answers

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'

like image 67
Daniel Ormeño Avatar answered Sep 18 '22 22:09

Daniel Ormeño