0

How can I add onClick attribute to this button using JS?

<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt">BUY NOW</button>

  • 3
    Does this answer your question? [Add onclick event to newly added element in JavaScript](https://stackoverflow.com/questions/3316207/add-onclick-event-to-newly-added-element-in-javascript) – LeeLenalee Sep 09 '21 at 16:02
  • You should try like this - – Rajeev Singh Sep 15 '21 at 10:36

3 Answers3

0

You can do it using Jquery:

"your element".addEventListener('click', function(){ 
     alert('hey');
 }, false);
John
  • 25
  • 7
0

you can use the JS function .addEventListener(), Here you'll find a well done explenation of It.

What I sugger you to do is to add an Id to your button tag and then use the document.getElementById() (if you don't know what this JS function does read this) to find your button and apply to It the .addEventListner() function to add a click behaviour.

I made a simple code example below, take a look at It and let me know if this answer is what you're searching for.

document.getElementById('myButton').addEventListener('click', () => {
  document.getElementById('myButton').classList.toggle('toggled');
});
button {
  width: 100px;
  height: 50px;
  background: #ccc;
  border: 0;
  outline: 0;
}

button:hover {
  cursor: pointer
}

button.toggled {
  background: red;
}
<html>

<head></head>

<body>
  <button type=submit id="myButton">
      CLICK ME
    </button>
</body>

</html>
Longino
  • 110
  • 7
0

If you want to do it in js, you will have to either use .addEventListener() function or .onClick() function that are triggered whenever the button is clicked

you can also use the .onClick inside of your html

<button type="submit" name="add-to-cart" value="41" class="single_add_to_cart_button button alt" onClick="function_name">BUY NOW</button>

sidenote: if you want to access the button element inside your javascript you can add an Id to your button tag and then use the document.getElementById() or use let var = document.getElementByClass() but be aware to use var[0] to access the button element in case you filtered it by class

yashsh
  • 81
  • 11