-2

I have a button. I need to make it clickable only once. But it does not have onclick attribute. And I cannot change HTML. This has to be done only with JS. How do I do it?

<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt">
  BUY NOW
</button>
Andy
  • 53,323
  • 11
  • 64
  • 89
  • disable the button after the click ... use on click handler... – Tushar Sep 10 '21 at 14:12
  • You can find here: https://stackoverflow.com/questions/57641554/how-to-make-onclick-function-execute-only-once – ikhvjs Sep 10 '21 at 14:12
  • it's silly, it is not by disabling a submit button that we can prevent the sending of a form. Any return on an input allows to send a submit – Mister Jojo Sep 10 '21 at 14:15

2 Answers2

1

You can attach a click handler to the button and set its disabled property to true:

const button = document.querySelector('button[name="add-to-cart"]');

button.addEventListener('click', function () {
  button.disabled = true;
});
<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt">BUY NOW</button>

If you ever need to re-enable the button, that would be additional logic of course. But it looks like this button is intended to submit a form which will change the page context anyway.

David
  • 188,958
  • 33
  • 188
  • 262
0

You can an event listener ('click') and change add the attribute. After that, remove the event listener.

victorfau
  • 143
  • 2
  • 14