The v-model in Vue does not function correctly when used with a single index within an array

I am encountering a situation with a series of input fields, including a checkbox and a dropdown button in each row. Additionally, there is a button to add a new row of inputs.

When the checkbox is checked, it should disable the dropdown menu and make it non-required.

<template>
  <div>
    <tr v-for="(item, i) of timesheet.items" :key="i">
    <div>
        <td>
            <input 
                type= "checkbox"
                v-model="checked"
                id= "{{ 'disable' + i }}" 
                v-on:click= "disable(i)"
            >
        </td>
        <td>
            <select2 
                :id="'project_id-' + i" 
                v-bind:class="{
                    'is-invalid': item.project_id.$error,
                    'is-valid':
                    item.project_id.$dirty &&
                    !item.project_id.$error,
                }"
            >
                <option value="">Select</option>
                <option v-for="(project) in projects" 
                    :selected="project.id == timesheet.project_id" 
                    :key="project.id" 
                    :value="project.id">{{ project.name }}</option>
            </select2>
        </td>
        <td>
            <button 
                type="button" 
                class="btn btn-sm btn-primary" 
                @click="itemCount++"
            >Add Row
            </button>
        </td>
    </div>
    </tr>
  </div>
</template>
<script>
    import { required, minLength } from "vuelidate/lib/validators";
    export default {
        data() {
            return {
                checked: false,
                timesheet: { items: [{ project_id: "" }] },
            }
        },
        validations() {
            if (!this.checked) {
                return{
                    itemCount: 1,
                    timesheet: {
                        items: {
                            required,
                            minLength: minLength(1),
                            $each: { project_id: { required }}
                        }
                    }
                }
            }else{
                return{
                    timesheet: {
                        items: {
                            required,
                            minLength: minLength(1),
                            $each: { project_id: {} }
                        }
                    }
                }                
            }
        },
        watch: {
            itemCount(value, oldValue) {
                if (value > oldValue) {
                    for (let i = 0; i < value - oldValue; i++) {
                        this.timesheet.items.push({
                            project_id: "",
                            checked: false,
                        })
                    }
                } else {
                    this.timesheet.items.splice(value);
                }
            }
        },
        methods: {            
            disable(index){
                const check = 
                        document.getElementById('project_id-' + index).disabled
                $('#project_id-' + index).attr('disabled', !check);
            }
        },        
    }
</script>   

The initial checkbox behavior works as intended, but upon adding a new row, the new row is always pre-checked and behaves oppositely. My question is how can I correct my v-model?

Answer №1

Upon reviewing your code, I have noticed a few issues that need attention.

Firstly, the checkbox is using an attribute

id= "{{ 'disable' + i }}"
, which is not allowed. You should instead use :id="'disable' + i" for proper interpolation in attributes.

Secondly, it seems unclear where itemsCount is defined. Assuming it falls under data.

Thirdly, all checkboxes are sharing the same v-model, causing them to behave synchronously and change together when one is clicked. This is due to using the checked model under data for all checkboxes.

Lastly, while defining

timesheet: { items: [{ project_id: "" }] }
, you later add items using
this.timesheet.items.push({ project_id: "", checked: false })
indicating you intend to have a checked property for each item (checkbox). To achieve this, add a checked property to items in data and use it as the v-model for your checkboxes as shown below:

  data() {
    return {
      itemCount: 1,
      timesheet: { items: [{ project_id: "", checked: false }] },
    };
  },
<input
  type="checkbox"
  v-model="item.checked"
  :id="'disable' + i"
  v-on:click="disable(i)"
/>

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

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

Oops! It seems like you've stumbled upon a 404 error on Django

I need to retrieve the price value immediately after a product is selected in the sale form. The sale form includes fields for price, quantity, and product. Once a user selects a product, the price of that product should populate the input box for price. T ...

The server is unable to process your request to /graphql

I've encountered an issue while setting up the GraphiQL API. I keep receiving the error message "Cannot POST /graphql" on both the screen and network tab of the console. Despite having similar boilerplate code functioning in another project, I'm ...

Struggling to Manage and Preserve Cookies in Browser While Using React App Hosted on GitHub Pages and Node.js Backend Running on Render

I've encountered a challenge with setting and storing cookies in the browser while utilizing a React application deployed on GitHub Pages and a Node.js backend hosted on Render. Let me explain the setup and the issue I'm facing: Setup: Frontend ...

What is the most efficient method for managing window properties and child components in React/Redux?

My <Layout> component loads different child components based on the page. Some of these children may have tabs, while others may not. This variation in content affects how scrolling should work and consequently influences the structure of the scroll ...

Navigate the child div while scrolling within the parent div

Is there a way to make the child div scroll until the end before allowing the page to continue scrolling when the user scrolls on the parent div? I attempted to use reverse logic Scrolling in child div ( fixed ) should scroll parent div Unfortunately, it ...

How to extract and display data when clicking on a Bootstrap switch

I have integrated BootStrap Switch like this: <?php while ($arr = mysql_fetch_array($res)) { ?> <td class="center"> <?php if ($arr['status'] == 1) { ?> <input class="switch" type="checkbo ...

"Effortlessly Populate Address Fields with Google Autocomplete and Vue.js: A Step-by-

I am new to Vue.js and I am exploring the autocomplete API to automatically populate the address fields in my form when a user types and selects an address from the dropdown menu. The code provided in the documentation uses Vanilla JavaScript, but I would ...

Display buttons when hovering with React

Seeking assistance with implementing functionality in a React application where buttons for editing and deleting display only when the mouse hovers over the corresponding row. Currently, the implemented code displays these buttons in all rows on hover. Sn ...

What is the best way to visually refresh a polymer element that displays data from a frequently changing URL?

Hey there! I'm currently facing an issue with displaying a polymer element that contains some important information. This element is supposed to appear when I tap on an icon, but for some reason it doesn't show up even after the data has been loa ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

What is the method for determining the new point coordinates and direction vector after a rotation of degrees in three.js?

How can I determine the coordinates of point A to H after rotating a certain number of degrees and aligning them with direction vector (-42, 51, 11) using three.js? Thank you in advance for your help and please forgive any mistakes in my English. Best reg ...

Tips for updating the minimum value to the current page when the button is pressed on the input range

When I press the next button on the current page, I want to update the value in a certain way. https://i.stack.imgur.com/XEiMa.jpg I have written the following code but it is not working as expected: el.delegate(".nextbtn", "click", f ...

Unraveling and interpreting all incoming requests to my Node.js application

Looking for a simple method to identify and decipher all encoded characters in every URL received by my Node.js application? Is it possible to achieve this using a middleware that can retrieve and decode symbols such as & ? ...

What is the best way to interact with my component in React?

As a newcomer to Reactjs, I have a question regarding my current setup: The components in my project include navComponent.js, stackComponent.js, and nav.js I am trying to pass data from stackComponent.js to navComponent.js so that the nav.js data can be ...

The function "useLocation" can only be utilized within the scope of a <RouterProvider> in react-router. An Uncaught Error is thrown when trying to use useLocation() outside of a <Router>

When attempting to utilize the useLocation hook in my component, I encountered an error: import React, { useEffect } from 'react'; import { useLocation } from 'react-router-dom'; import { connect } from 'react-redux'; import { ...

Tips for sending data to Jade templates:1. Use the `locals`

Review the code below user.js exports.index = function (req, res){ res.render('user', { id: req.params.id }); }; user.jade body - var x = #{id} div.container div.headpic if (x < 10) ...

Using ui-grid to show cells as drop-down menus

I have a ui-grid example where one of the columns represents gender ('Gender': male, female...). The json data binding to the grid only contains code types like (1, 2, 3...). However, I want to display the gender name such as 'male' if ...

Comparison Between Object and Array

When inputting the values {2,4,45,50} in the console, 50 is displayed. However, assigning these values to a variable results in an error: var a = {2,4,45,50} Uncaught SyntaxError: Unexpected number Can you explain this concept? ...

The HTML 5 video is not functioning properly on an iPad, and the layout of the iPad has black areas on the sides

Having some trouble with an HTML 5 project where the video plays on Chrome and Safari PC browsers but not on iPad. The task at hand is to get it working in portrait mode only, with the video playing when tapped/clicked. <!doctype html> <!--[if ...