-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
  • 61,948
  • 13
  • 68
  • 95

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
  • 208,112
  • 36
  • 198
  • 279
0

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

victorfau
  • 45
  • 1
  • 4
  • 18