1

I have an HTML button like so:

<div class="row text-center">
   <button id="button1" type="submit" class="btn btn-primary">Submit</button>
</div>

I'd like to add an onclick behavior for it via Javascript. It should call another function. I have tried this:

$("#button1").addEventListener("click", showAlert());

However, the browser is complaining that $(...).addEventListener is not a function. What should I do instead?

4
  • jquery on api.jquery.com/on Commented Jun 5, 2017 at 18:20
  • Possible duplicate of add onclick event to newly added element in javascript Commented Jun 5, 2017 at 18:21
  • addEventListener works on DOM objects. jQuery wraps up the DOM into its own array and has its own methods for doing things. Better to stick with one or the other, mixing and matching gets confusing -- fast. Commented Jun 5, 2017 at 18:22
  • Right good suggestions Commented Jun 5, 2017 at 18:22

3 Answers 3

1

With jQuery you can use .on():

$("#button1").on("click", showAlert);

or

$("#button1").click(showAlert);

addEventListener is a plain JavaScript method and you're trying to use it on a jQuery object. You could dereference the jQuery object using .get(0) and use it like:

$("#button1").get(0).addEventListener("click", showAlert);

or

$("#button1")[0].addEventListener("click", showAlert);

but there's really no reason.

Sign up to request clarification or add additional context in comments.

Comments

0

try jquery function:

$("#button1").click(function() {
.. whatever you want to do on click, goes here...
}) ;

Comments

0

You could try the following:

$( "#button1" ).bind( "click", showAlert);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.