Once the maximum total of all input fields has been reached, prevent any further input in the remaining

I run an online store where I offer a box of assorted flavor bagels with a maximum of 12 flavors per box. Each flavor has its own number input field, as seen in the screenshot linked below.

https://i.sstatic.net/eSU09.png

While I have successfully used JavaScript to limit each individual flavor field to a maximum of 12, I am now seeking a way to disable the other input fields once the total quantity across all fields reaches 12.

The current code snippet calculates the sum of all fields but currently only prevents each individual field from exceeding 12.

My goal is to restrict the combined total of all fields to no more than 12, thus completing the box of 12 bagels.

const totalMaxQty = 12;

getAllInputs.forEach(allInputs);

function allInputs(value) {
    value.addEventListener("input", function(e) {
        e.preventDefault();
        sumTotal();
    });
}

function sumTotal() {
    let sumValue = document.querySelectorAll('.wapf-field-input input[type=number]');
    let currentTotal = 0;

    for (let i = 0; i < sumValue.length; i++) {
        if (parseInt(sumValue[i].value)) {
            currentTotal += parseInt(sumValue[i].value);
        };
    }
}

for (let i = 0; i < getAllInputs.length; i++) {
    getAllInputs[i].max = totalMaxQty;
}

Please note that I am looking for vanilla JavaScript solutions only.

Answer №1

It appears that the sumTotal() function is not returning any value, so simply calling it within allInputs will not produce any result.

function sumTotal() {
    let sumValue = document.querySelectorAll('.wapf-field-input input[type=number]');
    let currentTotal = 0;

    for (let i = 0; i < sumValue.length; i++) {
        if (parseInt(sumValue[i].value)) {
            currentTotal += parseInt(sumValue[i].value);
        };
    }
return currentTotal

}

Regarding disabling the input fields, my recommendation is to utilize event delegation.

Place all input fields and their labels in a container, then set the event listener on the container. This way, you won't need to individually set an event listener on each input field using a loop.

const container = document.getElementById("container")



container.addEventListener("input", handleInputs )

    function handleInputs() {

         let currentTotal=sumTotal()

         if (currentTotal===12) {

            for (let i = 0; i < getAllInputs.length; i++) {
    getAllInputs[i].disabled = true;
                                    }
                                }
                            }

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

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...

Transform an array of strings into properties of an object

Looking for a way to map an array to a state object in React? Here's an example: const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"] Assuming you have the following initial state: state = { options:{} } You can achieve ...

The Javascript setTimeout Function Prolongs Its Operation

Currently, I have a web app index page that performs two main tasks. Firstly, it geocodes the user's location and stores it in a JavaScript variable called "variableToSend." Secondly, it sends this data to mySQL using a PHP script after a delay of 10 ...

Error: The function setDarkTheme is not defined

Every time I click on the Dark button to apply dark theme on my page, I encounter an error. It seems like the error lies in the onClick function of the button and I can't seem to figure it out. Error message App.js import { useState } from 'rea ...

Using forRoot does not trigger Angular lazy loading functionality

I have implemented a lazy load module that needs to expose providers by utilizing the forRoot convention and returning the following code: @NgModule({ imports: [RouterModule.forChild([ {path: "", component: LazyComponent}, ])], declarations: [La ...

looping through a collection of objects with partially distinct attributes

How can you iterate over an array of objects to retrieve the results of every previous game played? I encountered difficulties while attempting to iterate over non-existent values. The desired result is an array structured like this: newArr: [ { ...

Preserve the order of post types using jQuery sortable in the WordPress Admin panel

I am working with a custom post type called 'items' and I want users to be able to set a global order for these items. The goal is to have the ability to rearrange the items in a specific order using jQuery UI's sortable() function. However, ...

The state 'dash' is experiencing issues with its parameters in ui-router

Setting up a demonstration to highlight an issue I am facing with sibling components and states. Encountering the following error: https://i.sstatic.net/uUsF8.png Not sure what could be causing this, as our current app has it set up like this: params: ...

What methods can be used to eliminate superfluous `require(...)` or `import "...` statements while working with Rollup?

Currently, I am in the process of developing a library named share which will be utilized in various other services. To bundle this library, I have opted for Rollup.js. share serves as a common library accessed by multiple services, therefore it is essent ...

Set up counters for a variety of Owl Carousel sliders

I am looking to set up multiple owl carousel sliders, where each slider has a counter to track its position. I want the counters to update independently, but I'm running into issues with them not working correctly. Each slider should display a counte ...

Tips for automatically verifying coupons and adjusting prices

My current task involves implementing a coupon feature on the checkout page using an AJAX request to validate the coupon and adjust the price accordingly. However, when the checkout view is loaded, I encounter an error message: The first argument in the ...

What is the best way to activate an alert or swal function just once instead of repeatedly?

I am just starting to learn Angular. Currently, I have an application that contains two variables related to the status of financial transactions. These variables are: tab1TrxMessage, which holds any important messages, and tab1TrxStatus that indicates wh ...

What steps should I take to address the error message "TypeError: express-validator is not a function

I am currently utilizing express-validator version 6.4.0 and encountering an error when running the server. I have attempted to implement custom validation by organizing separate files for validator, controller, and routes. Here is the primary server file ...

Tips for sending information to select2 version greater than 4.0

I'm exploring the use of select2 for the first time and wondering if someone could assist me. I want to pull data from a static array. Can you offer any guidance on how to achieve this? This is the code I currently have: $(document).ready(function( ...

Combine PHP, jQuery, and AJAX to retrieve multiple values simultaneously

I have been using jQuery AJAX for my projects. When I make an AJAX call to a PHP page, it normally returns a single value to the success function of AJAX. However, I am now looking to retrieve multiple data individually. How can I achieve this? This is th ...

Step-by-step guide on utilizing $.each() for generating an interactive tooltip within datepicker Jquery

My Jquery datepicker displays a tooltip with the name of each holiday during a hover effect. I encountered a bug where the tooltip does not work when using $.each() instead of a for loop to display the tooltip. Here is the code snippet: $(".datepicker ...

Is it secure to store the access token within the NextAuth session?

Utilizing a custom API built with Node.js and Express.js, I have implemented nextAuth to authenticate users in my Next.js application. Upon a successful login, the date is stored in the nextAuth session and can be accessed using the useSession hook. To acc ...

Displaying all API data by default in Vue.js, even with filters, sorting, and search enabled - how can it be done?

I am currently utilizing Vue.js version 3 and below is the code snippet: <template> <h5>List of Products</h5> <h3>Filter</h3> <button v-on:click="resetOptions">Reset</button> & ...

The SVG image created is not appearing on the screen

I'm working on a JavaScript project to display SVG elements, but I'm encountering an issue with the "image" element. For some reason, when I create the image element dynamically, it doesn't appear in the browser. However, if I manually copy ...

Updating and deleting table rows dynamically using Ajax with the help of node.js and mongoose

I have a project where I am using Node.js to create an ajax table. The main functionality is that I can update rows without refreshing the entire page and also delete tasks. However, there are some issues with the functionality as shown in the image below. ...