Ways to enable or disable Javascript buttons based on a specific condition

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

Upon loading this page, I am looking to deactivate the (-) button if the value between these buttons is set to 1.

1)hbs code

<tbody>

    {{#each products}}

     <tr>

     <h1 id="Quantity" hidden>{{this.quantity}}</h1>

     <td><img src="/product-images/{{this.product._id}}.jpg" style="width:70px;height:70px" alt=""> 
  </td>

     <td>{{this.product.Name}}</td>

     <td>Rs.{{this.product.Price}}</td>

     <td>

     <button class="btn btn-info mr-3 cart-item-count" id="button(-)" 
   onclick="changeQuantity('{{this._id}}','{{this.product._id}}','{{../user._id}}',-1)">-</button>
 
     <span id="{{this.product._id}}">{{this.quantity}}</span>

     <button class="btn btn-info mr-3 cart-item-count" id="button(-)" 
    onclick="changeQuantity('{{this._id}}','{{this.product._id}}','{{../user._id}}',1)">+</button>

     <td>

     <button type="button" class="btn btn-danger">Remove</button>

     </td>

     </tr>

     {{/each}}

     </tbody>

2)Array of products

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

3)Code for Enabling and Disabling Buttons

 let Quantity = document.getElementById('Quantity').innerHTML
    console.log(Quantity)
    if (Quantity == 1) {
        document.getElementById('button(-)').disabled = true
    } else {
        document.getElementById('button(-)').disabled = false
    }
    
    function changeQuantity(cartId, proId, userId, count) {
        count = parseInt(count)
        let quantity = parseInt(document.getElementById(proId).innerHTML)
        let qty = quantity + count
        console.log(qty)
        if (qty > 1 ) {
            document.getElementById('button(-)').disabled = false
        } else if (qty == 1 || qty==10) {
            document.getElementById('button(-)').disabled = true
        }

        if(qty==10){
            document.getElementById('button(+)').disabled = true
        }else{
            document.getElementById('button(+)').disabled = false
        }

        $.ajax({
            url: '/change-product-quantity',
            data: {
                cart: cartId,
                product: proId,
                user: userId,
                count: count,
                quantity: qty
            },
            method: 'post',
            success: (response) => {

                document.getElementById(proId).innerHTML = quantity + count
                document.getElementById('total').innerHTML = response.total

            }
        })
    }

Note:

The provided code behaves correctly when there is only one product on the cart page. However, it does not work as expected when multiple products are listed. How can I individually control each product's buttons without affecting others?

Any suggestions on how to achieve this task effectively would be appreciated.

Answer №1

Assigning distinct identifiers to each product can facilitate the resolution of this problem.

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

UI-Router is malfunctioning, causing ui-sref to fail in generating the URL

I'm currently working on a project that involves Angular, Express, and UI-router for managing routes. While I've properly configured my $states and included the necessary Angular and UI-router libraries in my HTML file, I am facing an issue wher ...

Validating HTML and JavaScript syntax in the Ace editor

Currently, I am utilizing Ace Editor and facing the challenge of enabling live syntax checking for both HTML markup and JavaScript code within the editor. When I set "ace/mode/html" it only checks the HTML syntax. For example, in the following code snippe ...

Simulating MongoDB's DeleteResult with Mockito for Java Testing

I am encountering an issue with a unit test where I am unable to mock DeleteResult for the Java code under test, leading to a NullPointerException. The test is running on JUnit. Is the problem related to the Filters in the delete statement? @InjectMoc ...

Integrating an API with a Discord bot using an embedded link in Discord.js

I am currently in the process of creating a bot that can generate and embed links to display manga titles, tags, and other information based on user-input digits. I have been exploring an API called this and I am eager to learn the most effective method ...

Angular 4: Utilizing reactive forms for dynamic addition and removal of elements in a string array

I am looking for a way to modify a reactive form so that it can add and delete fields to a string array dynamically. Currently, I am using a FormArray but it adds the new items as objects rather than just simple strings in the array. Here is an example of ...

How to eliminate undefined values from a dropdown selection in AngularJS

Blockquote When choosing a material from the column, the first option is showing as undefined. How can I remove undefined from the drop-down list? What changes need to be made in the HTML/JSON data for this to work properly? Blockquote var app = ang ...

Execute the function only if the checkbox has been selected

Just starting out with angular.js and I wanted to create an html list with checkboxes. My goal was to trigger a javascript function when a user checks a checkbox. <input id='box' ng-model='" + key + "' ng-change='graphquery(&b ...

Unraveling the mysteries of interpreting the jsben.ch benchmark results

After testing three fibonacci algorithms on jsben.ch, it's clear that the first one is the fastest and even received an award icon: https://i.sstatic.net/ilfDz.png However, I'm curious about the numbers next to the code block results. What do t ...

Using JSON to Search in MongoDB

Recently, I have come across a json document with a specific structure as detailed below: { "125": { "name": "sample name one", "age" : 22, }, "126": { "name": "sample name two", "age" : 27, }, "127": { ...

Is there a way to detect when a user has recently updated their Chrome Extension in order to send them notifications?

I have implemented an info button in my extension, where a red dot appears on the top right corner to alert users of new updates whenever they update the extension. Currently, I achieve this by storing a row in localStorage when users view the updates. If ...

What steps should I take to ensure that model updates are applied by NgJsTree?

One of the challenges I encountered in my project involved integrating various technologies such as JQuery, JSTree, Angular, and NgJsTree. Despite updating the treeData model, the changes were not being reflected in the tree structure. tcwsApp.servi ...

Having trouble with JSON results not displaying properly. Unexpected output when using jQuery, Ajax, and JSON together

I’m struggling with a <input> field that is supposed to show live ajax results in a <div> as you type, similar to an auto-suggest feature. However, the issue I'm facing is that it only displays one result and not the expected multiple re ...

Using webpack's hash in JavaScript for cache busting

Can someone guide me on adding a hash to my js file name for cache-busting purposes? I've researched online but still uncertain about where to include the [hash] element. Any help would be appreciated. Provided below is a snippet from my webpack.conf ...

I am encountering an error with setTimeout(): Timeout { _called: false }

I have been experimenting with creating a function that generates a random number and then adds 5 to it after a 3-second delay This is what I have attempted: const add5 = (randomNum) => { return randomNum + 5 } // Function for you to get start ...

What is the reason for XMLHttpRequest.status being equal to 0 in all browsers except for Internet Explorer?

I am encountering a frustrating issue... After developing a standalone RESTful.NET webservice using C#, I noticed that when I make a XMLHttpRequest to fetch JSON data, all browsers, except for IE, fail to retrieve the data. The problem lies in the status ...

Once I have verified the accuracy of certain $_POST variables, I am looking to close my window. Is there a way to achieve this using JQuery?

<?php if($_POST["some_variable"]){ echo "this window should be closing now"; } ?> How do I implement a JQuery function to close the window? The code snippet below demonstrates how the window was initially opened... $('.new_windo ...

Ways to refresh the information displayed on the view when the observable data is updated

I am using an observable called getContentfulEntry to retrieve data, while also passing data from another observable known as stateService. this.langSubscription = this.stateService.getLanguage() .subscribe(val => { this.lang = val; ...

Sending text content using AJAX

Recently, I've delved into the world of AJAX and JavaScript while working on a project in JSP. My goal is to submit text entered in a textarea using a JavaScript button. The first submit button worked fine initially, but upon posting, I ended up with ...

The system is unable to locate the command "nvm"

Lately, I've been experimenting with using nvm to manage different versions of node. After successfully installing nvm on my Mac OS Catalina(10.15.6), I was able to easily switch between versions through the terminal. However, when attempting to do t ...

What is the best way to find the actual position of this user within my array?

I found this example in the Vue JS documentation here When using a filtered v-for, how can I obtain the actual index of a user in the array, rather than the index of the current iteration? <div id="filter-by-example"> <ul> <li v-for= ...