Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value.

Currently, my ViewModel is configured as follows:

var viewModel = new Vue({
    el: "#OrderPickContainer",
    data: {
        ProductTitle: "",
        Batches: [],
        totalSelected: 0
    },
    methods: {
        // Other methods are located here
    }
});

The structure of my table is like this:

<table class="table table-striped">
    <thead>
        <tr>
            <th>Select</th>
            <th>Batch Number</th>
            <th>Available</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
        <template v-for="batch in Batches">
            <tr> 
                <td><input type="checkbox" /></td>
                <td>{{ batch.BatchNumber }}</td>
                <td>{{ batch.AvailableQuantity }}</td>
                // Within each row, there is an input field that should update `totalSelected`. The challenge lies in binding these inputs together to reflect changes collectively.
                <td><input type="number" min="0" class="form-control" /></td>
            </tr>
        </template>
        <tr>
            <td></td>
            <td></td>
            <td><strong>Total:</strong></td>
            <td><strong>{{ totalSelected }}</strong></td>
        </tr>
    </tbody>
</table>

The struggle I am facing revolves around finding a way to connect all the number textboxes in different rows to a single Vue variable for tracking overall selection count.

Answer №1

Your request in the question was to calculate the sum of checked values only. Below is a solution that computes the total quantity for selected items.

To achieve this, you can add a Selected and a Quantity property to each batch object and utilize them within a computed function.

console.clear()


var viewModel = new Vue({
    el: "#OrderPickContainer",
    data: {
        ProductTitle: "",
        Batches: [
          {
            Selected: false,
            BatchNumber: 1,
            AvailableQuantity: 10, 
            Quantity: 0
          },
          {
            Selected: false,
            BatchNumber: 1,
            AvailableQuantity: 10, 
            Quantity: 0
          }
        ],
    },
  computed:{
    totalSelected(){
      return this.Batches
        .reduce((acc, v) => {
          if (v.Selected) acc = acc + v.Quantity
          return acc
        }, 0)
    }
  }
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9c9f8faad8c4d8c4dc">[email protected]</a>/dist/vue.js"></script>
<div id="OrderPickContainer">
<table class="table table-striped">
    <thead>
        <tr>
            <th>Select</th>
            <th>Batch Number</th>
            <th>Available</th>
            <th>Quantity</th>
        </tr>
    </thead>
    <tbody>
        <template v-for="batch in Batches">
            <tr> 
                <td><input type="checkbox" v-model="batch.Selected" /></td>
                <td>{{ batch.BatchNumber }}</td>
                <td>{{ batch.AvailableQuantity }}</td>
                
                <td><input type="number" min="0" class="form-control" v-model.number="batch.Quantity" /></td>
            </tr>
        </template>
        <tr>
            <td></td>
            <td></td>
            <td><strong>Total:</strong></td>
            <td><strong>{{ totalSelected }}</strong></td>
        </tr>
    </tbody>
</table>
</div>

Answer №2

If you wish to connect the input with a variable inside the batch:

<input type="number" min="0" class="form-control" v-model="batch.qty"/>

Then create a computed property to calculate their total:

computed: {
    totalQty: () => {
       return this.Batches.reduce((sum, batch)=>{
           return sum + batch.qty;
       }, 0);
    }
}

Ensure that qty is already defined in your batches for it to work correctly.

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

javascript get the value of the text field

Is there a way to calculate even and odd numbers using a text field for entering the range of values and a select tag to choose between even and odd? How can I retrieve the value from the text field in order to pass it to the calculation function? Custom ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

Export data from Angular Material data table to Excel format

I'm currently utilizing the angular material data table to showcase data in a tabular layout. I have a requirement to add a feature that enables the export of tabular data to an Excel sheet. Unfortunately, I haven't been able to locate any resour ...

Display the uploaded images from uploadify on the webpage

I am currently working on a PHP website that utilizes uploadify for users to upload portfolio images. While I have successfully implemented uploadify, I am now exploring the most effective way to display these uploaded images on the webpage without requir ...

Workbox background sync - Retrieving replayed API responses

Currently, I am utilizing the Workbox GenerateSW plugin and implementing the backgroundSync option within runtimeCaching. You can find more information in the documentation here. This powerful plugin enables me to monitor APIs and successfully retry faile ...

Displaying a DIV after entering text into an <input> field using JavaScript

Attempting to create a JavaScript function that will show/hide a 'DIV' after entering some text into an input field. I have successfully written the function, but I am struggling to make it only work when the user enters a value greater than 8. ...

Tips for accessing the value of a dynamically created textbox using JavaScript

Hello everyone, I have a couple of questions that I need help with. I am currently working on developing a social networking website similar to Facebook. On this platform, there are multiple posts fetched from a database. However, I am facing an issue w ...

Issue with `npm run generate` command in Nuxt.js causing failure to create `index.html` file

Why is it that all static routes and dynamic routes are generated except for index.html? My nuxt-config.js file contains the following: const staticRoutes = [ '/about', '/contact', '/portfolio' ] const dynamic ...

"Localhost:3000 is down for Nuxt.js, experiencing technical difficulties

Transitioning from React to Vue.js, I encountered an issue while trying to run my localhost on Port 3000, resulting in the error message below. It seems like there's a problem with the server. Below, I've provided the installation process for cl ...

A step-by-step guide on how to refresh a circular loading indicator

I have been researching how to create a circular progress bar using canvas, and I came across this code. After making some modifications to the code snippets that I found online, I encountered an issue - I can't seem to reload the circular path once i ...

Error: Trying to use Router without providing a middleware function. Please make sure to pass a valid middleware function while using Router

While working on my express application with MongoJS, I encountered an issue where despite returning a function, it was showing that an object has been returned instead. To address this, I made sure to include module.exports=router in my JavaScript file. H ...

Using Angular JS to connect Promises while preserving data

There have been discussions about chaining promises, but this scenario presents a unique challenge. I am currently working on making multiple http get requests in my code. The initial call returns an array, and for each object in this array, another http c ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Linking the location of the pop-up to the currently selected text box

I am currently experimenting with setting the top and left values relative to the selected_element (which is active at the time of triggering the popup) in a manner similar to a tooltip. I attempted to use $().position() in combination with jQuery, but it ...

Why is the Axios instance/function not being passed the argument?

I am currently working on refactoring a next.js App that has a functioning axios call. However, I have encountered an issue with my new function not receiving arguments. The problem consists of two main components: my next.js page and an external custom m ...

Running a Vue.js single-page application (SPA) in Docker without the need for N

The official Vue.js documentation features a straightforward example of dockerizing a single page application. You can find the example here. According to the documentation, the application will run on localhost:8080 Is it possible to bind the applicatio ...

Video tag with centered image

For a current project, I am in need of rendering a centered image (a play button) at runtime on top of a video based on the UserAgent. If the userAgent is not Firefox, I want to display the image as Firefox has its own playEvent and button on top of the vi ...

NextJS 13 causes tailwind to malfunction when route group is utilized

I've encountered an issue in my NextJS 13 application where Tailwind classes are no longer being applied after moving page.tsx/layout.tsx from the root directory to a (main) directory within the root. I suspect that there may be a configuration that i ...

Having trouble constructing the Grand-Stack-Starter api because babel-node is not being recognized

As I endeavor to create the initial api for the Grand Stack Starter, I encounter difficulties every time I try to execute npm start: >nodemon --exec babel-node src/index.js [nodemon] 1.18.7 [nodemon] to restart at any time, enter `rs` [nodemon] watchi ...

Retrieve information using the request npm package

Currently, I am in the process of developing an application with express js. My approach involves using request(v-2.88.2) to retrieve data from an api. request(url, function(error, request, body) { var data = JSON.parse(body); }); My goal is to utili ...