How To Know Which Button Is Clicked In Jquery

When dealing with multiple buttons on a page, it’s often necessary to know which button was clicked in order to perform a specific action or function. In this blog post, we will cover how to determine which button is clicked using jQuery.

jQuery Click Event

The first step to knowing which button is clicked in jQuery is to bind a click event to the buttons. This click event will listen for any button click and run a function when it occurs. To keep the examples simple, we will be working with three buttons:

<button class="my-button" id="button-1">Button 1</button>
<button class="my-button" id="button-2">Button 2</button>
<button class="my-button" id="button-3">Button 3</button>

Now, let’s bind the click event to these buttons using jQuery:

$(document).ready(function() {
$('.my-button').on('click', function() {
// Click event function
});
});

Determining the Clicked Button

Now that we have bound the click event to our buttons, we can determine which button was clicked using the this keyword inside the click event function. Let’s console.log the clicked button:

$(document).ready(function() {
$('.my-button').on('click', function() {
console.log(this);
});
});

By console.logging this, we can see the entire button element that was clicked. But often, we need more specific information like the button’s ID or any other attribute. To get the ID of the clicked button, we can use the attr() function in jQuery:

$(document).ready(function() {
$('.my-button').on('click', function() {
var buttonID = $(this).attr('id');
console.log(buttonID);
});
});

Now, when we click any of the buttons, the console will display the ID of the clicked button. This allows us to perform specific actions based on which button was clicked. For example, we can use a switch statement to handle different actions for different button IDs:

$(document).ready(function() {
$('.my-button').on('click', function() {
var buttonID = $(this).attr('id');

switch(buttonID) {
case "button-1":
// Handle Button 1 click
break;
case "button-2":
// Handle Button 2 click
break;
case "button-3":
// Handle Button 3 click
break;
}
});
});

And that’s it! You now know how to determine which button was clicked using jQuery. By using the this keyword inside the click event function and jQuery’s attr() function, you can perform specific actions based on the clicked button’s attributes.