How to Create a jQuery Button Click Function

To access a button click with jQuery use the click() method and pass the function to handle the event as the first argument.

 

Let's create a button with an ID attribute and a jQuery function to do something when it is clicked.

 

<button type="button" id="bar">Click me</button>
$('#bar').click(function() {
  alert('Button clicked do something');
});

 

Access the Button that was Clicked

To access the button that was clicked with jQuery, use the this keyword inside a selector.

 

<button type="button" id="bar">Click me</button>
$('#bar').click(function() {
  var btn = $(this);
  console.log(btn[0].id)
});

 

jquery