[Vuejs]-Checkbox form array data Vue 2

0👍

I think you are trying to mix the old jQuery or javascript way of doing things with Vue framework. You should not have to set id on <input> elements to capture or set its value.

The correct way to do this is as follows:

new Vue({
    el: '#app',
    data: function() {
        return {
            yards: [
                {id: 1, name: 'test', selected: true},
                {id: 2,name: 'test 2', selected: false},
                {id: 3,name: 'test 3', selected: false},
                {id: 4,name: 'test 4', selected: true}
            ]
        };

    },
    template: `
        <div class="list-of-yards"> <!-- You cannot use v-for on the top-level element -->
            <label for="jack" v-for="yard in yards">
                <input type="checkbox" v-model="yard.selected"> {{yard.name}}
            </label>
        </div>
    `,
});

Here is a jsFiddle of the above code: https://jsfiddle.net/z48thf9a/

Things to note:

  1. You cannot use v-for on the template tag itself
  2. You cannot use v-for on the top-level element just inside template. The template should contain one and only enclosing element, typically a <div>
  3. There is no need to set id on input elements. You need to use v-model for your model-view bindings

If you still have issues, please provide a jsFiddle to debug further.

Edited after comment #1 and #2:

My above response is focused more on constructing the Vue component and rendering the list with proper binding to the checkboxes.

To get the checked items into a separate array, you can use a computed property in the same component to run through the original array this.yards and create a new array of selected items only.

Here is the jsFiddle for capturing the checked values: https://jsfiddle.net/z48thf9a/1/

You may modify the above to capture only the id part, and rename selectedYards to newSchedule or whatever your app requires.

I am not sure if I understood your question correctly, and if this solves your issue. Can you please provide more code samples?

Leave a comment