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

Scrolling to specific ID scrolls only in a downward direction

I have been using fullpage.js for my website and I am facing an issue. When I create a link and connect it to an id, everything works perfectly. However, I am unable to scroll back up once I have scrolled down. Here is the HTML code: <a href="#section ...

Creating a compact, production-ready code using the webapp generator in Gulp

I recently used the webapp generator to scaffold a project, but encountered an issue where the project only worked when accessed through localhost and not when opening the files directly in the browser with a file scheme. The URL http://localhost:9000/ cor ...

Splitting with Regex - One Time Operation

Here is some of my Jquery code along with Regex: $("[class^=ipsum-img],[class^=ipsum-img-]").each(function(){ var x = $(this).attr("class"); console.log(x.length); if (x.length>8) { var m = x.split(/(\d+)[^-]*$/g); cons ...

What methods can a Discord Bot use to respond with specific messages to individual users?

Hey there! I'm dipping my toes into the world of coding and thought it would be fun to create a Discord bot that gives different responses each time it's mentioned. Just so you know, I'm working with Discord.js version 13 for this project. ...

Expiration Alert: SSL Certificates for HERE Links will expire shortly

Our SSL certificates for the following URL's are approaching expiration: *.base.maps.ls.hereapi.com geocoder.ls.hereapi.com Do you have any information on when these URLs will be updated with new certificates? ...

`Need help testing flow.js file uploads using Selenium?`

My AngularJS SPA allows users to upload files using the ng-flow wrapper for flow.js. I am currently in the process of setting up automated e2e tests with Selenium, but I am facing challenges when it comes to testing the file uploading mechanism triggered b ...

Executing a script within an ASP.NET MVC Project

Currently, I'm in the process of developing a project in MVC that requires using AJAX to fetch XML from an external source. However, I have encountered a challenge where I am unable to directly make the AJAX call due to a XMLHttpRequest same domain po ...

How to Develop a Custom getText() Function for a Selenium Element?

Creating a custom Selenium getText() method that can retrieve either the node text or the node plus child text of an element is my current challenge. The default behavior of Selenium appears to utilize the Xpath .//string() method which includes the text o ...

What is the best way to incorporate a mongoose model into another model?

I have two different models that I am working with. In the user model, I want to include an array of Requests, and in the Request Model, I want to have User as an attribute (without including the password). How can I achieve this? var userSchema = new S ...

To prevent the default alignment in case the text exceeds the input length, stop the automatic alignment

I have a query regarding an input field with a maximum length of 4 characters. The appearance is such that these 4 characters seem to be delineated by borders which are actually 3 lines displayed above the input field. When I enter the fourth character, a ...

AngularJS Alert Timer Setting

Is there a way to display the timer value in AngularJS? I have included the following code for the timer tag: <timer interval="1000" countdown="100">{{countdown}}</timer> I have also added an alert function in the script.js file to display th ...

Vertically animating an image using jQuery

I have been experimenting with trying to make an image appear as if it is floating by using jQuery to animate it vertically. After some research, I stumbled upon this thread: Animating a div up and down repeatedly which seems to have the solution I need. H ...

The function is malfunctioning following the alert

I am experiencing an issue with my renumbering list function. I have a delete button on the list that triggers a confirmation alert, but after the alert is shown, the renumbering function stops working. Here is my script: <script type="text/javascript ...

What is the best way to disable list items in a UI?

Check out my assortment: <ul class="documents"> <li class="list_title"><div class="Srequired">NEW</div></li> <li class="doc_price>1</li> <li class="doc_price>2</li> <li c ...

JavaScript code for Tree not functioning correctly on Internet Explorer

Seeking assistance to fix a bug in my JavaScript program. The code works perfectly on Google Chrome and Firefox, however it encounters an error in Internet Explorer 8 as indicated below. Any suggestions on how to resolve this issue would be greatly appreci ...

CRITICAL ERROR: CALL_AND_RETRY_LAST Memory allocation failed - JavaScript heap exhausted

I am experiencing issues when trying to search using npm: npm search material However, I keep getting this error message: npm WARN Building the local index for the first time, please be patient FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaSc ...

What is the best way to show a tooltip alongside highlighted text?

How can I display a tooltip (using qTip) next to selected text? The code below captures the selected text in the console, but the tooltip is not displayed. <div class='test'>Actual text will be much longer...Test Test Test Test Test Test T ...

Implementing Pagination in Vuetify: A Step-by-Step Guide

I am looking to implement pagination using the Vuetify framework in my VueJS project. The Vuetify Pagination component: <v-pagination v-model="pagination.page" :length="pagination.total / 5" :total-visible="pagination.visible" ...

Using Node.js to seamlessly read and upload files with Dropbox API

I am utilizing the Dropbox API to retrieve a file from the node.js file system and then transfer it into a designated Dropbox folder. The transfer process is successful, but the file ends up being empty, with a size of 0 bytes. var path = require("path") ...

Troubleshooting issue: AngularJS NVD3 line chart directive does not refresh after data update (not updating in real time)

I am currently facing an issue with the nvd3-line-chart directive in my AngularJS application. The chart does not redraw when I change the underlying model... As a newcomer to AngularJS, there may be something obvious that experienced programmers will not ...