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?

  • jquery on http://api.jquery.com/on/ – Huangism Jun 05 '17 at 18:20
  • Possible duplicate of [add onclick event to newly added element in javascript](https://stackoverflow.com/questions/3316207/add-onclick-event-to-newly-added-element-in-javascript) – Asif Raza Jun 05 '17 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. – Jeremy J Starcher Jun 05 '17 at 18:22
  • Right good suggestions –  Jun 05 '17 at 18:22

3 Answers3

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.

j08691
  • 204,283
  • 31
  • 260
  • 272
0

You could try the following:

$( "#button1" ).bind( "click", showAlert);
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
chickahoona
  • 1,914
  • 14
  • 23
0

try jquery function:

$("#button1").click(function() {
.. whatever you want to do on click, goes here...
}) ;
R Dhaval
  • 536
  • 1
  • 9
  • 21