Incapable of deactivating button in Vue JS when quantity equals zero

I'm currently working with Vue to create a quantity selector component where users can increase or decrease input values. However, I am facing an issue where I need to disable the minus button when the value is zero or lower. Below is the HTML and JS code I've developed so far, but unfortunately, the alert and updateButtonDisabled() function are not functioning as expected.

Here's the HTML code with click functions:

<div class="input-group-prepend">
  <span id="subButton" class="input-group-text" @click="decrement()">-</span>
</div>

<input v-model="form.quantity" type="number" class="form-control" id="Quantity" value="1" min="1" {% if product.variants.size == 1 %}max="{{ product.variants.first.inventory_quantity}}"{% endif %}>

<div class="input-group-append">
  <span class="input-group-text" @click="increment()">+</span>
</div> 

And here's the JS code along with data:

    data(){
      return {
        form: {
          id: document.getElementById('variant-id').value,
          quantity: document.getElementById('Quantity').value
        }
      }
    }

      updateButtonDisabled(){
        // If quantity is less than or equal to zero, disable the minus button
        if(this.form.quantity <= 0) {
          document.getElementById("subButton").setAttribute('disabled', 'disabled');
        }
        else {
          document.getElementById("subButton").removeAttribute('disabled');
        }
      },
      increment () {
        this.form.quantity++
        this.updateButtonDisabled();

      },
      decrement () {
        if(this.form.quantity <= 0) {
          alert('Negative quantity not allowed')
        } else {
          this.form.quantity--
        }
         this.updateButtonDisabled();
      }

If anyone could provide assistance, it would be greatly appreciated. Thank you!

Answer №1

A <span> element does not respond to the disabled attribute being added.

There are two options available: using a different DOM element that changes its appearance when the disabled attribute is present, such as the <button> element.

Alternatively, you can add a class (for example, disabled) to the element and customize its style as desired:

 span.disabled { 
   opacity: 0.5;
   pointer-events: none;
 }

It is recommended not to manipulate the DOM directly within your component. Vue has built-in functionality to handle this automatically. Here's an example of how you can achieve this in Vue:

<button :disabled="form.quantity <= 0">

Or, by applying a class:

<span :class="{ disabled: form.quantity <= 0}">

While there's nothing inherently wrong with manual manipulation, relying on Vue for reactive updates is more efficient. It's like driving a sports car instead of pushing it down the street.

Lastly, you no longer need to call updateButtonDisabled(). Vue's reactivity takes care of this automatically.

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

Tips on Creating a Display None Row with a Sliding Down Animation Using Javascript

I am working with a table that has some hidden rows which only appear when the "show" button is clicked. I want to know how I can make these hidden rows slide down with an effect. Here's the snippet of my code: function toggleRow(e){ ...

Guide on setting up the Facebook Messenger customer chat SDK in Nuxt and Vue

Recently, I attempted to integrate the Facebook Messenger customer chat SDK into my Nuxt app. Potential Solution 1 (0% success): I experimented with the https://www.npmjs.com/package/vue-fb-customer-chat package but encountered issues. The package' ...

What could be causing Vite to not locate the '.vue' loader during the Vue 3 migration build process?

Currently in the process of upgrading a Vue 2 project to Vue 3 by utilizing the migration build and vite (https://v3-migration.vuejs.org/breaking-changes/migration-build.html#overview) I've completed steps 1-4 (skipping 4 as I'm not using typesc ...

I am encountering ESLint and Vetur warnings when using the <script setup> tag in templates, despite having them included in my code

When utilizing <script setup> in Vue 3, I am receiving warnings on my methods as they no longer require a return statement. Any insights into why these warnings are appearing? https://i.sstatic.net/Zg4M0.png https://i.sstatic.net/ee18q.png ...

Unexpected behavior: Controller action method retrieves undefined value upon jQuery Ajax request

I'm currently working on my ASP.NET Core 3.1 project and implementing cascading dropdown functionality with jQuery. I've set it up so that changing the value of the first dropdown (Region) should automatically update the second dropdown, Location ...

Retrieve information from a row by clicking on it, then present it in a dialog box for editing

I'm working on a project using Angularjs to retrieve data from a table row when it's clicked and then display the data in an editable dialog box. I need help with implementing this feature. Here is my current progress: <table> ...

Difficulty comprehending/implementing callback functions

After reviewing this discussion and chatting about it, I have come to understand that utilizing a callback function is the most effective approach! "Is using a callback the only solution for acquiring a link from the server via ajax, storing it in a varia ...

Display a secure background image using Angular 6

Even though I have successfully generated the image url to avoid any sanitizer errors, my background image is still not displaying. Is it necessary for me to utilize the "changingThisBreaksApplicationSecurity" property in order for the image to appear corr ...

Is it possible to start a vue-cli project without using Git?

After setting up a vue-cli project, I noticed that Git is always initialized by default. Is there any way to create a template without Git being included? ...

Leveraging the 'passport.isAuthenticated()' method for evaluating numerous user roles within a Node.js application

Below is the code snippet for my custom isAuthenticated function: var isAuthenticated = function (req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/'); }; Here's a route that uses PassportJs with the custom isA ...

JavaScript in IE/Edge may not run correctly if it is loaded from the cache

I am facing a peculiar problem with Internet Explorer (IE) and Edge. Upon initially loading a page, everything functions perfectly fine. However, if I navigate away from the page to another page on the same website, JavaScript errors start showing up on th ...

Easiest method to change cursor to 'wait' and then return all elements to their original state

On my website, there are certain CSS classes that define a specific cursor style when hovered over. I am trying to implement a feature where the cursor changes to a "wait" image whenever an AJAX call is initiated on any part of the page, and then reverts b ...

Update WooCommerce Mini-cart with ajax refresh

I'm having an issue with my custom plugin where everything is working properly, except for the fact that the mini cart is not updating after adding items. I have tried various methods to trigger a refresh, but so far nothing has worked. Below is a sni ...

function called with an undefined response from ajax request in React

Hello, why am I getting the response "callback is not defined"? Component 1: console.log(getUserGps()); Component 2: import $ from 'jquery' export const getUserGps = () => { $.ajax({ url: "https://geolocation-db.com/jsonp", ...

Guidelines for implementing a vuex getter within the onMounted hook in Vue

Currently, my process involves fetching data from a database and storing it in vuex. I am able to retrieve the data using a getter in the setup method, but I would like to manipulate some of that data before the page is rendered, ideally in the onMounted m ...

When using Material UI Autocomplete, the selected option should automatically be populated in the input field

When a user navigates through the choices using the arrow keys on their keyboard, I extract the value from the highlighted option to update the current input value (which has its own state). However, when the title or value of the option is saved as the i ...

React: Issue with array rendering order after initial render

After the initial rendering of my array in the correct order, any subsequent changes to it result in the same rendered order. Let's consider this scenario: initializeArray() { this.state = { test_array: [1,2,3,4] } let self = t ...

Traverse an array to generate a horizontal chart

My goal is to dynamically create a horizontal table by mapping through an array, similar to the design shown in this image. https://i.sstatic.net/YfElb.png This is how I am currently mapping through the array: const glanceGames = this.state.gameData.map ...

Puppeteer failing to detect dialog boxes

I'm attempting to simulate an alert box with Puppeteer for testing purposes: message = ''; await page.goto('http://localhost:8080/', { waitUntil: 'networkidle2' }); await page.$eval('#value&apos ...

Setting the current time in an Animation using ThreeJS

I'm utilizing skinning and skeletal animation within ThreeJS. My goal is to navigate through an animation by moving backward and forward, as well as jumping to specific locations within the sequence instead of the usual looping behavior. The animatio ...