'How to detect submit form button was clicked

I've two button on submit form.

1. Add to Cart Button

2. Buy Now Button

I need to add disable class if the button was clicked,

submitForm: function (form) {
        var addToCartButton, buyNowButton, self = this;

        if (form.has('input[type="file"]').length && form.find('input[type="file"]').val() !== '') {
            self.element.off('submit');
            // disable 'Add to Cart' button

            addToCartButton = $(form).find(this.options.addToCartButtonSelector);
            buyNowButton = $(form).find(this.options.buyNowButtonSelector);

            if(addToCartButton){
                addToCartButton.prop('disabled', true);
                addToCartButton.addClass(this.options.addToCartButtonDisabledClass);
            }else if(buyNowButton){
                buyNowButton.prop('disabled', true);
                buyNowButton.addClass(this.options.buyNowButtonDisabledClass);
            }


            form.submit();
        } else {
            self.ajaxSubmit(form);
        }
    },


Solution 1:[1]

Try it like this (JQuery):

          $(".classNameOfButton").click(function(){functionName(this)});

Solution 2:[2]

Pure Javascript, here you go :)

document.addEventListener('DOMContentLoaded', () => {
  const button = document.querySelector("button");

  button.addEventListener("click", (e) => {
    e.target.disabled = true
  }) 
});
  1. wait for DOM content to get loaded (probably not necessary in your case as it will be part of larger codebase
  2. get button element you need
  3. addEventListener for click to that element
  4. set disabled to true

About event.target

https://developer.mozilla.org/pl/docs/Web/API/Event/target

Codepen:

https://codepen.io/pen/

Solution 3:[3]

JS:

// Disable default Event (Browser reloading..)
const formElement = document.getElementByID("formID");
formElement.addEventListener("submit", () => {

event.preventDefault(); });

const button1 = document.getElementByID("button1");
button1.addEventListener("click", (event) => {
 // do something...
     e.target.classList.add("disabled");
});


const button2 = document.getElementByID("button2");
button2.addEventListener("click", (event) => {
 // do something...
     e.target.classList.add("disabled");
});
  1. Prevent Default Action of a form submit button (reload site)
  2. get both buttons and attach an "click" event listener
  3. If clicked add "disabled" class

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 azrahel
Solution 3