Steps to apply V-model to elements

I am currently facing an issue with giving dynamically created input fields dynamic v-models from JSON data using vue.js.

Here's what I'm doing:

new Vue({
  el: '#app',
  data() {
    return {
      totalAmt: 500,
      paymentMode: [{
        "PAYMENTCODE": "SW",
        "PAYMENTNAME": "Swiggy"
      }, {
        "PAYMENTCODE": "BB",
        "PAYMENTNAME": "uber Eats"
      }, {
        "PAYMENTCODE": "WE",
        "PAYMENTNAME": "Zomato"
      }]
    }
  },
  computed: {
    balAmt() {
      return 0 - this.totalAmt
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <label>Total Amt</label>
    <input type="text" v-model="totalAmt">
  </div>
  <div v-for="mode in paymentMode" :key="mode.PAYMENTCODE" class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
    <label>{{mode.PAYMENTNAME}}</label>
    <input type="text">
  </div>
  <div>
    <label>Bal Amt</label>
    <input type="text" :value="balAmt">
  </div>
</div>

What I am trying to do is:

There are two fields, Total Amt and Bal Amt. In the Total Amt field there is a value, and in Bal Amt, it should be the same value as Total Amt but negative (e.g., Total Amt=500, then Bal-Amt=-500 when the page loads).

Now, there are three dynamic input fields where users can enter values. When a user types, for example, 50 in the input field for Swiggy, I want to calculate Total Amt - the entered amount (i.e., Total Amt-the field amount).

For static fields, this calculation can easily be done. But for dynamic fields, I am unsure how to achieve this.

Answer №1

To make calculations similar to the totalAmt, include a v-model for each input and assign it to "mode.Amount". Then within the balAmt, find the total sum of all inputs and subtract it from the totalAmt.

new Vue({
  el: '#app',
  data() {
    return {
      totalAmt: 500,
      paymentMode: [{
        "PAYMENTCODE": "SW",
        "PAYMENTNAME": "Swiggy"
      }, {
        "PAYMENTCODE": "BB",
        "PAYMENTNAME": "uber Eats"
      }, {
        "PAYMENTCODE": "WE",
        "PAYMENTNAME": "Zomato"
      }]
    }
  },
  computed: {
    balAmt() {
      // Calculate the sum of amounts in paymentMode
      const sum = this.paymentMode.reduce((a, b) => a + (+b.Amount || 0), 0);
      return sum - this.totalAmt;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <label>Total Amount</label>
    <input type="text" v-model="totalAmt">
  </div>
  <div v-for="mode in paymentMode" :key="mode.PAYMENTCODE" class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
    <label>{{mode.PAYMENTNAME}}</label>
    <input type="text" v-model="mode.Amount">
  </div>
  <div>
    <label>Balance Amount</label>
    <input type="text" :value="balAmt">
  </div>
</div>

Answer №2

const app = new Vue({
  el: '#app',
  data() {
    return {
      totalAmount: 500,
      paymentMethods: [{
        "paymentCode": "SW",
        "paymentName": "Swiggy",
        amount: 0
      }, {
        "paymentCode": "BB",
        "paymentName": "Uber Eats",
        amount: 0,
      }, {
        "paymentCode": "WE",
        "paymentName": "Zomato",
        amount: 0
      }]
    }
  },
  computed: {
    otherAmount() {
      let amount = 0
      this.paymentMethods.forEach(method => {
        amount += Number(method.amount)
      })
      return amount
    },
    balanceAmount() {
      return 0 - (this.totalAmount - this.otherAmount)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div>
    <label>Total Amount</label>
    <input type="text" v-model="totalAmount">
  </div>
  <div v-for="method in paymentMethods" :key="method.paymentCode" class="form-group col-xs-12 col-sm-12 col-md-4 col-lg-4 col-xl-4">
    <label>{{method.paymentName}}</label>
    <input type="text" v-model="method.amount">
  </div>
  <div>
    <label>Balance Amount</label>
    <input type="text" :value="balanceAmount">
  </div>
</div>

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

How can I display the most recent offcanvas opening at the top of the page?

The issue I'm facing is related to the offcanvas3 opening behind offcanvas2. It appears like this: $("#open-offcanvas2").on("click", function(){ $("#offcanvas2").offcanvas("show") }) $("#open-offcanvas1").on("click", function(){ $("#offcanvas1" ...

Switch the ng-bind-html option

Dealing with a string in my scope, I must determine whether I want the HTML escaped or not. A boolean value helps to decide if the HTML should be escaped or left as is. Snippet Check out some of my code examples below: $scope.result = "<b>foo</ ...

Error: The property 'updateOne' cannot be read because it is undefined

I have been struggling to update an array in my MongoDB database, despite following the steps outlined in the official documentation. I can't seem to make it work. Can anyone provide assistance? I went through the official documentation, but unfortun ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

Can the value of a variable be passed as seen in the JavaScript code snippet?

I'm wondering if I'm on the right track with generating random colors when a button is clicked. Here's my code: randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16); // --- more code --- changeHeaderColor() { con ...

Tips for resolving a jspdf naming collision situation

In my react app, I am utilizing various jsPDF libraries as shown below: For exporting tables as HTML: import jsPDF from 'jspdf'; import "jspdf-autotable"; For converting SVG to PDF: const svg2pdf = require('svg2pdf.js'); con ...

The PHP counter conceals the comma upon loading and does not display it permanently

I'm currently working on a PHP counter and encountering an issue with the comma display. I have implemented Number Format in a PHP function to print counter digits with commas every 3 digits, but the comma doesn't remain visible after the page lo ...

Show a specific div using jQuery fadeIn() when the user reaches the top of an HTML section

The code below has a specific purpose: 1) Determine the current scroll position. 2) Locate the parent article and determine its offsetTop for each .popup_next which represents a section on the site. 3) Calculate an offset value by adding 30px to the off ...

Discover all related matching documents within a string array

I am using a mongoose schema model with a field called tags which is an array of strings to store tags for each document. I need functionality where if I search for a specific tag, such as "test," it will return all documents with tags like "testimonials" ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

The Node.js engine isn't updating to support compatibility with Firebase functions

Encountered First Failure Below is the content of package.json "engines": { "node": "8.0.0" }, Error: The engines field in the functions directory's package.json is unsupported. You can choose from: {&quo ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Error message: Error in jQuery: Object is required for Internet

I have a button that is designed to trigger the opening of a jQuery UI Dialog when clicked. Strangely, it works perfectly in FF3, FF4, Chrome, and IE8 with ChromeFrame, but fails to function in regular IE8. The error message displayed simply states "Object ...

Having trouble with the clear button for text input in Javascript when using Bootstrap and adding custom CSS. Any suggestions on how to fix

My code was working perfectly until I decided to add some CSS to it. You can view the code snippet by clicking on this link (I couldn't include it here due to issues with the code editor): View Gist code snippet here The code is based on Bootstrap. ...

Best practices for implementing the map function with TypeScript

I'm currently working on mapping types in a DB using the Map function in JavaScript. This is my first time trying to do this, and I'm eager to learn but I've hit a roadblock. Here is the structure of the DB: const db = { data: [ { ...

This code encountered an Uncaught SyntaxError due to an invalid or unexpected token

Hey there, I've been struggling with an Uncaught SyntaxError: Invalid or unexpected token issue whenever I try to click on the edit or delete button. Can someone please help me figure out what's wrong with this code? I've spent hours looking ...

Scheduling classes based on their index or data attributes

Here is a code snippet demonstrating the use of a variable instead of a hardcoded value: var i = 1; if ($(this).attr('data-target="1"')){} To pass the variable i instead of 1, you can modify the code like this: if ($(this).attr('data-targ ...

How to remove elements from a JavaScript array: exploring the potential use of the delete function in JavaScript

I'm currently using Flot JS charts and I am attempting to completely remove a specific plot series from my data array either through jquery or plain javascript. Below is an example of what my data array consists of: [ { "label" : "Citrix PV Ether ...

Guide to simulating Twilio with Jest and TypeScript to perform unit testing

Please assist me in mocking a Twilio service that sends messages using Jest to mock the service. Below is the code I am working with: import { SQSEvent } from "aws-lambda"; import { GetSecretValueResponse } from "aws-sdk/clients/secretsmanag ...

Refreshing local storage memory on render with a custom Next.js hook

I recently developed a custom Next.js hook named useLocalStorage to store data in local storage. Everything is working fine, except for one issue - the local storage memory gets refreshed with every render. Is there a way to prevent this from happening? ...