Vue 2 checkbox form array data

Creating a checkbox list with a dynamic id and name:

Data:
yards[{id:1,name:'test'}] etc

HTML:
<ul class="checkbox-list">
     <template v-for="(yard, index) in yards">
                                <li>
                                    <input type="checkbox" 
                                        v-bind:id="'yardlist_'+yard.name"
                                        v-bind:value="yard.id"
                                        v-model="newSchedule.yards.id">
                                    <label v-bind:for="'yardlist_'+yard.name">{{ yard.name }}</label>
                                </li>
                                <li>
                                    <input type="text" 
                                        class="form-control"
                                        placeholder="Yard notes..."
                                        v-model="newSchedule.yards.notes">
                                </li>
                            </template>
                        </ul>

Storing selected checkboxes with id and notes field in an array:

newSchedule: {
            due_at: '',
            notes: '',
            users: [],
            yards: [{id:'',notes:''}]
        }

Error encountered when trying to access the index from the yards array: newSchedule.yards[index].notes - "TypeError: undefined is not an object (evaluating 'newSchedule.yards[index].id')"

Looking for suggestions on how to achieve this?

** Update ** Check out this example of what I'm looking to accomplish: https://jsfiddle.net/j7mxe5p2/13/

Answer №1

It seems like there might be some confusion between traditional jQuery or JavaScript practices and working with the Vue framework. There is no need to manually set the id attribute on <input> elements in order to capture or manipulate their values.

The preferred method of handling this situation 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">
            <label for="jack" v-for="yard in yards">
                <input type="checkbox" v-model="yard.selected"> {{yard.name}}
            </label>
        </div>
    `,
});

You can view a demonstration of this code on jsFiddle here: https://jsfiddle.net/z48thf9a/

A few key points to keep in mind:

  1. Avoid using v-for directly on the top-level element within the template tag
  2. Your template should contain a single enclosing element, typically a <div>, when using v-for
  3. Instead of setting individual id attributes on input elements, utilize v-model for seamless data binding

If you encounter any difficulties, feel free to provide a jsFiddle link for further debugging assistance.

Update following comments #1 and #2:

The initial response focuses on setting up the Vue component and correctly linking checkboxes to your data model.

To extract the checked items into a separate array, consider implementing a computed property within the same component that filters through the original this.yards array to create a new array containing only selected items.

For an example demonstrating this functionality, refer to this modified jsFiddle: https://jsfiddle.net/z48thf9a/1/

You can customize this approach to extract only the relevant data, renaming variables like selectedYards to suit your application's needs.

If additional clarification is required or if you have more code snippets to share, please provide them so we can better address your concerns.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encounter an error while decoding JSON using Swift 5.2: "Unexpected dictionary found instead of an Array<Any>."

After spending hours trying to debug my code, I am still unable to find the issue. Despite repeatedly checking my code and searching the internet for solutions, I haven't come across anything particularly helpful. The problem lies in my use of the fin ...

"Learn the process of incorporating a trendline into a line chart using Highcharts by manipulating the

I am facing difficulties in creating a trend line for a line chart. I have tried some old solutions but they did not work for me. Below is my current code: { "key": "003", "title": "Detections", "ty ...

Obtaining template attributes in CKEditor: A guide

I have been working with the template plugin in CKEditor to load predefined templates. Each template is defined as follows: templates: [ { title: "Quickclick 1", image: "template1.png", description: "Quickclick 1 template", html_et: "& ...

Troubleshooting: Why isn't setMetadata working in NestJS from authGuards

When I call my decorators, I want to set metadata for logging purposes. Within my controller, the following decorators are used: @Post("somePath") @Permission("somePermission") @UseGuards(JwtAuthGuard) @HttpCode(200) @Grafana( ...

"Utilizing a JavaScript array to track the start of the week and

I am encountering a logic problem with determining the start of the week. Below is a snippet of the code: WeekStarts(WeekN) { let WeekBD = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Sa ...

What is the best way to change a byte array into an image using JavaScript?

I need assistance converting a byte array to an image using Javascript for frontend display. I have saved an image into a MySQL database as a blob, and it was first converted to a byte array before storage. When retrieving all table values using a JSON ar ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

Issues with retrieving object from processed JSON data

I've been experimenting with the Twitter API and attempting to parse the JSON output. However, it seems like I'm making a mistake somewhere because I'm not achieving the desired result. Currently, I'm working in PHP. I started looping ...

What could be the reason for the "begin" script failing to execute?

I have a simple node and express application that works as expected, but I encounter an issue when trying to run the server from the script. When my script is set to "start", running the command simply opens my cmd. However, if my script is set to any oth ...

Guide for manually initiating the mouseleave event on a smartphone or tablet

Is there a way to change the color of a link to orange when it's hovered over? On mobile devices, the link should turn orange when touched and stay that way until the user clicks away. I'd like to manually trigger the mouseout event to remove th ...

Deploying an Angular 2 application using SystemJS and Gulp can sometimes feel cumbersome due to its

Although I have experience developing with Angular, I recently started working with Angular 2. After completing the quickstarter tutorial, I attempted to deploy the finished application on a server in production mode. My lack of experience with SystemJS a ...

Assigning a session variable through a dropdown selection

Currently, I am working on a custom WordPress theme that involves setting a session variable based on the value selected from a dropdown box. This session variable is then used to determine which container should be loaded. The code snippet below shows whe ...

Watching a Computed Value in EmberJS

What causes the discrepancy between the two sets of code? Utilizing computed: computed: Ember.computed('selected', function() { console.log('computed'); return this.get('selected'); }), observer1: Ember.observer(&ap ...

What is the syntax for utilizing cookies within the `getServerSideProps` function in Next.js?

I am struggling to pass the current language to an endpoint. Despite attempting to retrieve the language from a Cookie, I keep getting undefined within the getServerSideProps function. export async function getServerSideProps(context) { const lang = aw ...

The detailed record of this run can be accessed at:

npm ERR! code ENOTEMPTY npm ERR! syscall rename npm ERR! path /usr/local/lib/node_modules/expo-cli npm ERR! dest /usr/local/lib/node_modules/.expo-cli-dKBr48UN npm ERR! errno -39 npm ERR! ENOTEMPTY: The directory cannot be renamed because ...

What is the best way to ensure that the HTML page is only shown once all data from three JSON files has been fully

I have successfully parsed data from three different JSON files using the code below. //factory app.factory('myapp', ['$http', function($http) { function getLists() { var tab = [&a ...

Using Python within HTML with Python integration

df2 = pd.DataFrame(np.random.randn(5, 10)).to_html() myPage = """ <html> <body> <h2> Programming Challenge </h2> <form action="/execute" method="get"> <sele ...

Learn how to dynamically bind Font Awesome icons in Vue 3 with this easy tutorial

My v-for loop is functioning properly, but I'm having trouble getting the icon to display. How can I correctly bind it? It's worth noting that I have imported and returned the icon, and I am using font awesome in my project. Here are my imports ...

Updating cluetip content post webpage loading

I need to update the content within a cluetip after the page has finished loading. Imagine there's a button inside the cluetip and upon clicking it, I want it to disappear. Here is the cluetip setup: $('a.notice_tooltip').cluetip({activa ...

margin-top: automatic adjustment, with a minimum of 50 pixels

I am trying to add a minimum of 50px margin to the top of my footer tag using CSS, but I haven't been successful with the min() function. I'm not sure if I am overlooking something or if there is another correct approach to achieve this. * { ...