0

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);
        }
    },
Kevinzie
  • 103
  • 1
  • 5
  • 2
    Possible duplicate of [How can I get the button that caused the submit from the form submit event?](https://stackoverflow.com/questions/2066162/how-can-i-get-the-button-that-caused-the-submit-from-the-form-submit-event) -> You can use `document.activeElement` inside the vent handler to find out, which button was used to trigger the form submit (or if any of those buttons was used at all, because a form submit may also be triggered by pressing enter inside a text-field) – feeela Sep 19 '18 at 09:00

3 Answers3

1

Try it like this (JQuery):

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

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/

azrahel
  • 1,143
  • 2
  • 13
  • 31
0

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
filip
  • 628
  • 2
  • 8
  • 31