jQuery: How to Find Out Which Button Is Clicked

For example, you have many buttons on a web page for different jobs. So for triggering the correct action, you will have to know which button has been clicked. Here is the solution for this:

 

I assume that you have two buttons and you want to know which of them is clicked by the user. First write some CSS for the buttons.

[code type=”php”]
.thebuttons {
font-weight:bold;
border: 2px solid;
margin: 5px;
text-align: center;
float: left;
width: 100px;
}
[/code]

Now the HTML code:

[code type=”php”]
<span>Italic</span>
<span>Bold</span>
[/code]

JQuery Code:

[code type=”php”]
$(document).ready(function() {

$(“.thebuttons”).bind(“click”, function() {

alert(“Clicked Button is: ” + $(this).text()+ ” button”);

});
});
[/code]

In the above example, I used bind event to bind the click event. But you can also do this directly like below:

[code type=”php”]
$(document).ready(function() {
$(“.thebuttons”).click(function() {
alert(“Clicked Button is: ” + $(this).text()+ ” button”);
});
});
[/code]

Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment