The functionality of the change event seems to require the activation of the enter key in order to work

I am currently developing a quantity selector feature for an online store. The quantity selector includes:

  1. The minus button
  2. The quantity input field: whenever the user clicks on either the plus or minus buttons, the value is updated
  3. The quantity text: this is the quantity enclosed in <span> tags
  4. The plus button

Below is the HTML structure for the quantity selector:

<div class="product-form__input product-form__quantity">
  <label class="form__label">
    Quantity
  </label>

  <button class="quantity__button minus no-js-hidden" name="minus" type="button" disabled>
    -
  </button>

  <input class="quantity__input"
  type="number"
  name="quantity"
  id="Quantity-{{ section.id }}"
  min="1"
  value="1"
  form="{{ product_form_id }}"
  >

  <span class="quantity__text">1</span>

  <button class="quantity__button plus" name="plus" type="button">
    +
  </button>
</div>

The JavaScript code for this functionality is as follows, where the quantityPicker.init() function is invoked:

  • Updating the quantity input field's value each time the user interacts with the plus or minus buttons (calling the quantityPicker.onButtonClick() method)
  • If the quantity input field's value changes, then triggering the quantityPicker.onChange() function.
// Quantity picker
let
  quantityFields = document.querySelectorAll(".quantity__input"),
  quantityButtons = document.querySelectorAll(".quantity__button"),
  quantityPicker = {
    // Function to handle button clicks
    onButtonClick: function (event) {
      let
        button = event.target,
        picker = button.closest(".product-form__quantity"),
        quantity = picker.querySelector(".quantity__input"),
        quantityValue = parseInt(quantity.value),
        max = quantity.getAttribute("max") ? parseInt(quantity.getAttribute("max")) : null

        if (button.classList.contains("plus") && (max === null || quantityValue + 1 <= null)) {
          quantity.value = quantityValue + 1
        }
        else if (button.classList.contains("minus")) {
          quantity.value = quantityValue - 1
        }
    },
    // Function to handle input field changes
    onChange: function (event) {
      let
        field = event.target,
        picker = field.closest(".product-form__quantity"),
        quantityText = picker.querySelector(".quantity__text"),
        shouldDisableMinus = parseInt(event.target.value) === parseInt(field.getAttribute("min")),
        shouldDisablePlus = parseInt(event.target.value) === parseInt(field.getAttribute("max")),
        minusButton = picker.querySelector(".quantity__button.minus"),
        plusButton = picker.querySelector(".quantity__button.plus")
        
      quantityText.innerText = event.target.value

      if (shouldDisableMinus) {
        minusButton.setAttribute("disabled", "disabled")
      } else if (minusButton.getAttribute("disabled") === true) {
        minusButton.removeAttribute("disabled")
      }

      if (shouldDisablePlus) {
        plusButton.setAttribute("disabled", "disabled")
      } else if (plusButton.getAttribute("disabled") === true) {
        plusButton.removeAttribute("disabled")
      }
    },
    // Initialize the quantity picker
    init: function () {
      // Handle button click events
      quantityButtons.forEach(quantityButton => {
        quantityButton.addEventListener("click", function (event) {
          quantityPicker.onButtonClick(event)
        })
      })

      // Handle input field change events
      console.log(quantityFields)

      quantityFields.forEach(quantityField => {
        console.log(quantityField)

        quantityField.addEventListener("change", function (event) {
          console.log("Value changed!")
          quantityPicker.onChange(event);
        })
      })
    }
  }

  quantityPicker.init()

However, there seems to be an issue where the change event does not trigger when clicking on the plus or minus buttons, only when directly typing into the input and submitting by pressing Enter. How can we ensure that the quantityPicker.onChange() function executes every time the value updates without requiring the user to press Enter?

Answer №1

Thinking about implementing the input event. It triggers every time there is an input

Answer №2

After some exploration, I managed to find the solution to this query. When either the change or input events are altered dynamically, they do not function as expected. To resolve this issue, I utilized the dispatchEvent() method to manually trigger these events, as demonstrated in the snippet below:

quantity.dispatchEvent(new Event('input'));

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

Encounter issue when attempting to insert multiple items into MongoDB

// Import User and Item Models const User = require('../../models/User'); const Item = require('../../models/Item'); router .post('/login/:id', passport.authenticate('jwt', {session: false}), (req, res) => { ...

What is the best way to trigger events upward in a Backbone View hierarchy?

Running a backbone app with a structured view system, here's a simplified version of how it looks: NewsListView = Backbone.View.extend({ el: $('li#newspane'), initialize: function() { _.bindAll(this); }, render: f ...

Having trouble saving post data using ajax in django

I am encountering an issue with saving my partial '_dim' while viewing the main template 'sheet_form_create.html'. Every time I try to post the data for my '_dim' partial, I receive an error. Any assistance would be greatly ap ...

Passing no data in Angular.js ui-router.Angular.js ui-router

Within my Ionic application, there is a need to pass parameter(s) from one sub-view to another. Initially, the parameters are successfully passed as expected. However, upon returning to the first sub-view and then navigating to another sub-view, the parame ...

Choosing bookmarkable views in Angular 5 without using routes

I'm currently working on a unique Angular 5 application that deviates from the standard use of routes. Instead, we have our own custom menu structure for selecting views. However, we still want to be able to provide bookmarkable URLs that open specifi ...

Make your Bootstrap table interactive with editable icons

I have incorporated a bootstrap table into my react application and I am looking to add a feature where each row has an edit icon. When clicked, the entire row's elements should become editable. Currently, this is how my table looks: <Table classN ...

Tips for integrating a back button functionality with AJAX requests

My single page web application allows users to enter genre, date range, and other inputs before making an ajax post request to a Java Spring MVC server. Despite everything working well, I now want to implement a back functionality. If a user wants to go b ...

Keep the sidebar in place as soon as one of its child elements reaches the top, ensuring that the child element remains on top of it with an automatically

Having an issue making my sidebar stick at the correct height and produce the desired effect. Here's my code: https://jsfiddle.net/oavgLrf9/ The problem arises when I want my sidebar to add a fixed class when the second module reaches the top. Both ...

A step-by-step guide on executing a callback function once the animation has finished with frame-motion

I'm facing an issue with my component called AnimatedText. After the animation is complete, I want the words filled in the underlineLines prop to be underlined. How can I achieve this? I attempted using the onAnimationEnd function, but it didn't ...

Navigate to a pathway, trigger an error notification, and transfer to a different destination

Currently, my project involves working with nodejs, expressjs, and javascript... I have implemented a "middleware" function designed to prevent access to certain routes by users who are not logged in. However, I am facing an issue where I cannot send an a ...

Transferring a method through two layers of hierarchy

I'm currently working on a fun little game project, but I've hit a roadblock when it comes to passing a particular method down to its grandchildren components. Despite finding similar discussions on this topic, none seem to address my specific qu ...

Can you explain the distinction between "typeof str" and "typeof(str)" when working with JavaScript?

Can you identify the distinction between these two lines of code? if (typeof errorMessage !== undefined) {} and if (typeof (errorMessage) !== undefined) {} ...

Please filter out all items in the onChange function without needing to call all items again

When I implement a drop-down search and filter items, I encounter an issue where once I filter them, I am unable to filter them further because they are already 'cut' and filtered. Here is my code snippet: <select class="select" (cha ...

What could be causing this JSON object error I'm experiencing?

res.send({ customerDetails:{ fName, lName, }, applicantDetails:{ [ {primaryApplicant:{fName1,lName1}}, {secondaryApplicant:{fName2,lName2}}, {thirdA ...

Problem with loading messages in VueI18n locale

Utilizing the vueI18n package for language localization in our application, we fetch the locale messages object via an api call. Within our config file, we have specified the default language which is used to load the locale before the creation of app.vue. ...

Creating event listeners for slides transitioning forwards and backwards in Swiper JS: How can it be done?

Is there a way to create separate functions for when the slider moves forward and when it moves back? The documentation only mentions an event (slideChange) that triggers whenever the slide changes in any direction. If you have any suggestions or methods ...

Utilizing asynchronous operations in MongoDB with the help of Express

Creating a mobile application utilizing MongoDB and express.js with the Node.js MongoDB driver (opting for this driver over Mongoose for enhanced performance). I am aiming to incorporate asynchronous functions as a more sophisticated solution for handling ...

Difficulty in extracting data from child elements of JSON documents

Below is the JSON String: "book_types": { "type": "1", "books": [ { "name": "default", "cover": null, "lastUpdated": { "microsecond": 114250, "ctime": "Fri Aug 9 01:27:45 ...

Top option for managing an excess of pins on Google Maps

Let me walk you through my Google Maps setup process: To start, I retrieve the locations of all markers (usually under 300) from a database and send them to JavaScript in JSON format. Within JavaScript, I parse the JSON data, iterate through the marker a ...

Record every function within the array prototype

Exploring methods that can be accessed on an array object: > console.log(Array.prototype) [] undefined > console.log(Array.prototype.push) [Function: push] Is there a way to view or log all properties/methods accessible on an object's prototyp ...