The challenge of implementing dynamic table rows in Vue.js

While using Vue.js to dynamically create table rows, I encountered an issue where the price in the previous row's textbox gets cleared when adding a new row. The problem seems to be related to setting the price value only when selecting a product, but not when manually typing it in.

The desired behavior is to obtain the price value from an axios call every time a new row is added. However, currently, the price value remains unchanged if manually typed before adding a new row.

I need assistance in resolving this issue and identifying where the mistake might be in my code.

Here is a snippet of my template code:

<tr v-for="(invoice_product, k) in invoice_products" :key="k">
<td scope="row" class="trashIconContainer">
  <button class="btn-outline-danger btn-sm rem_row" type="button" @click="deleteRow(k, invoice_product)"><i class="fa fa-times"></i></button>       
</td>   
<td>
      <select id="product" name="product" v-model="invoice_product.product_name" @change="setprice($event)">
            <option v-for="(spro, index) in supplierproducts" :key="index" :value="spro.id">{{ spro.name }}</option>
          </select>
</td>
<td>
    <input class="textbox text-right" type="text"  v-model="invoice_product.product_price" 
    />
</td></tr>
 

And here is a section of my script code:

data() {
    return {
      errors: {},
      valid: true,
      suppliers: [],
      supplierproducts: [],
      input: {
        supplier: ""
      },
      invoice_subtotal: 0,
        invoice_total: 0,
        invoice_tax: 5,
        invoice_products: [{
            product_name: '',
            product_price: ''
        }]
    }
  },
  methods: {
    setprice(e)
    {    
      this.axios.get('/getproduct/' + e.target.value).then((response) => {        
        if (response.status == 200) {
          e.target.parentElement.nextElementSibling.getElementsByTagName('input')[0].value = response.data[0].price
        }
        else {
          console.log(response.data);
        }
      })
    },
     addNewRow() {
        this.invoice_products.push({});
    },

Answer №1

  1. It is crucial to remember to update data instead of manipulating the DOM directly in Vue.js, as Vue will automatically handle the DOM changes for you.
  2. Always remember to set default values for reactive data properties.

<tr v-for="(invoice_product, k) in invoice_products" :key="k">
<td scope="row" class="trashIconContainer">
  <button class="btn-outline-danger btn-sm rem_row" type="button" @click="deleteRow(k, invoice_product)"><i class="fa fa-times"></i></button>       
</td>   
<td>
      <select id="product" name="product" v-model="invoice_product.product_name" @change="setprice(invoice_product)">
            <option v-for="(spro, index) in supplierproducts" :key="index" :value="spro.id">{{ spro.name }}</option>
          </select>
</td>
<td>
    <input class="textbox text-right" type="text"  v-model="invoice_product.product_price" 
    />
</td></tr>

data() {
    return {
      errors: {},
      valid: true,
      suppliers: [],
      supplierproducts: [],
      input: {
        supplier: ""
      },
      invoice_subtotal: 0,
      invoice_total: 0,
      invoice_tax: 5,
      invoice_products: [{
        product_name: '',
        product_price: ''
      }]
    }
  },
  methods: {
    setprice(product) {
      this.axios.get('/getproduct/' + e.target.value).then((response) => {
        if (response.status == 200) {
          //Remember, always update the data and let Vue handle the DOM changes
          product.product_price = response.data[0].price
        } else {
          console.log(response.data);
        }
      })
    },
    addNewRow() {
     // Don't forget to provide default values for reactive data properties
      this.invoice_products.push({
        product_name: '',
        product_price: ''
      });
    },

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

Clicking the button will remove any previously applied CSS style using jQuery

Is there a way to remove the background color that was applied to a previously clicked button when clicking on another button? The current code successfully changes the background color of the clicked button upon hover, but it doesn't reset or remove ...

The functionality of $state.go within $stateChangeStart in the app.run is not functioning properly in AngularJS

Having some trouble getting $state.go() function to work. The $on('$stateChangeStart'...); is functioning properly, and I can see the console message when trying to access a protected state without permission. However, the $state.go('toState ...

What is the best way to update the data-url attribute with a new value using jQuery?

Initially, before the page loads: <a data-url="htts://xyz@..." class="mybuttons" data-type="facebook"> After page load, I dynamically update the data-url using jQuery: <a data-url="https://abc@..." class="mybuttons" data-type="facebook"> ...

Examine the syntax of JavaScript

I've been digging into a piece of code written by another person. My focus is on uncovering the JavaScript function that executes when the link below is clicked.... <a href="#subtabs_and_searchbar" id="finish_counting" onclick="$(' ...

Unexpected error when using Slack SDK's `client.conversations.open()` function: "User Not Found"

I am currently utilizing the Slack node SDK in an attempt to send private messages through a bot using user IDs: const client = new WebClient(process.env.SLACK_TOKEN); const sendMessage = async (userId) => { try { await client.conversations.open( ...

A pop-up modal that remains closed thanks to sessionStorage

I've been working on creating a modal that pops up after a short delay, but once closed, it shouldn't appear again unless the user closes the website and starts a new session. While I have successfully designed the modal, integrating sessionStora ...

Store the information retrieved from an Ajax call regarding an artist on the page, ensuring that it is only saved once for that

I have been working on a single-page application that utilizes the Spotify REST API and JQuery to enable users to search for an artist and display their information on the page. However, I want to ensure that the app saves details about each artist only ...

What is the best way to retrieve reactive data from a child component within a slot?

Currently, I am facing a scenario where a parent component is rendering a child component and passing a modal component (Modal.vue) into the child as a slot. In Parent.vue: <ChildComponent :id='1> <modal slot="modal" :postTitle="'test ...

What are the implications of incorporating listeners in redux action creators?

While developing my app, I have a feature that involves constantly monitoring location changes and updating the store accordingly. One question that has arisen is whether it would be beneficial to keep the listeners inside the action creator rather than th ...

Accessing and sending only the body part of an HTTP response in Angular 7 test cases: A comprehensive guide

Currently, I am working on creating unit test cases in Angular 7 for a Component that utilizes an asynchronous service. This is the content of my component file: submitLoginForm() { if (this.loginForm.valid) { // send a http request to save t ...

Threejs file exporter from Blender generating corrupted files

My Blender model seems to be causing issues: After using the threejs exporter in Blender 2.7, the exported json file contains numerous null or 0 values: { "metadata": { "formatVersion" : 3.1, "generatedBy" : "Blender 2.7 Exporter", ...

Retrieving information in Ionic

Having trouble fetching data from a server in my first ionic application. I keep getting an error that says "Cannot read Property" while trying to attach my code snippet. Here is what my code looks like: import { Component } from '@angular/core' ...

retrieve data from firestore and pass it as a parameter to a function

After successfully retrieving a field from Firestore and logging the correct information, I am now trying to set the name of my code as a reusable function. Below is the original code: db.collection('users').doc('' + sender_id).get(). ...

Update my React shopping cart with fresh items

I am currently dealing with an issue in my online food ordering system. Specifically, when I click on the add button to order an item, it updates the existing item in the cart instead of appending the new one as the next item. Highlighted below is a cruci ...

Send data with AJAX and PHP without refreshing the page

I have implemented the "add to favorite" feature on my WordPress project using a <form> submission. Each time I click on the add to fav button, it works fine, but the page always reloads which is quite annoying. To tackle this issue, I decided to imp ...

Troubleshooting a Vue.js formatting problem in Visual Studio 2019

Encountering an issue with VS2019 while attempting to format this code section. <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="milestone.ascx.cs" Inherits="uc.dms.milestone" %> <section class="content-header"> <h1> ...

Strange behavior exhibited by the HTML DataList component within an Angular application

I have created a simple component that displays a list of data and allows users to add new entries. <h6 *ngIf="withHeader"><label for="select"> {{title}} </label></h6> <label *ngIf="!withHeader" [ngClass]="{'required&apos ...

Ensure users follow step-by-step journey in Vue Material's steppers and connect each step to a designated path

I'm just starting out with web development and I have a question. I want to design a stepper with 5 tabs that restricts navigation - for example, you can't proceed to step 3 without completing step 2, and so on. If a user is on step 4 but wants t ...

Display information from Node.js on an HTML page

I am working on a nodejs project where I need to login on one page and display the result on another page using expressjs. Below is my code for login.ejs: <!DOCTYPE html> <html lang="en" dir="ltr"> <body> <form method="PO ...

I am eager to incorporate a hashtable in my JavaScript code, but unfortunately, I am encountering an unexpected

function MyHashTable(){ var totalSize = 0; var dataEntry = new Object(); this.addItem = function(key, value){ if(!isKeyPresent(key)){ totalSize++; } dataEntry[key] = value; } this.fetchValue = functi ...