how to know which button is clicked in jquery
How to Know Which Button is Clicked in jQuery
As a web developer, it is common to encounter a scenario where you need to know which button has been clicked by the user. In jQuery, there are different ways to achieve this, and I will explain them below.
Method 1: Using the Click Event
The simplest way to know which button is clicked in jQuery is by using the click()
event. Here's an example:
$('button').click(function() {
var buttonText = $(this).text();
console.log(buttonText + ' button is clicked.');
});
In this example, we are attaching a click()
event to all the button
elements on the page. When a button is clicked, the event handler function is executed. Inside the function, we are using the $(this)
keyword to refer to the button that triggered the event. We are retrieving the text of the button using the text()
method and logging it to the console.
Method 2: Using the Event Object
An alternative way to know which button is clicked in jQuery is by using the event
object. Here's an example:
$('button').click(function(event) {
var buttonText = $(event.target).text();
console.log(buttonText + ' button is clicked.');
});
In this example, we are attaching a click()
event to all the button
elements on the page. When a button is clicked, the event object is passed to the event handler function. We are using the event.target
property to refer to the button that triggered the event. We are retrieving the text of the button using the text()
method and logging it to the console.
Method 3: Using Data Attributes
If you have a large number of buttons and do not want to attach a separate event handler to each button, you can use data attributes to identify them. Here's an example:
$('button').click(function() {
var buttonText = $(this).data('button-text');
console.log(buttonText + ' button is clicked.');
});
<button data-button-text="Save">Save</button>
<button data-button-text="Cancel">Cancel</button>
<button data-button-text="Delete">Delete</button>
In this example, we are attaching a click()
event to all the button
elements on the page. When a button is clicked, we are retrieving the value of the data-button-text
attribute using the data()
method. We are logging it to the console.
These are some of the ways you can know which button is clicked in jQuery. Choose the one that suits your needs and use it in your code.