Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

271
Views
How to add onClick attribute to a button with JS?

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>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can do it using Jquery:

"your element".addEventListener('click', function(){ 
     alert('hey');
 }, false);
about 4 years ago · Juan Pablo Isaza Report

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>

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!