21

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.

1 Answer 1

27

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'

Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, thanks! Didn't realize you could add interpolation inside those tags.
No worries! You can as long as you use the :id notation, and you can also add bindings to values in your "view model"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.