How to detect which button is clicked in jquery?

Member

by charles , in category: JavaScript , 2 years ago

How to detect which button is clicked in jquery?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by dmitrypro77 , 2 years ago

@charles You can use $(this) to detect clicked button in jQuery and look into the code below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
<html>
<head>
    <meta charset="utf-8"/>
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script>
</head>
<body>
    <button id="button1" class="button-1">Button 1</button>
    <button id="button2" class="button-1">Button 2</button>
</body>
<script>
    $("button").on("click", function () {
        let id = $(this).attr("id")
        // Id of clicked button
        console.log(id)
        // Class of clicked button
        console.log($(this).attr("class"))
    })
</script>
</html>


by dee_smith , a year ago

@charles 

To detect which button is clicked in jQuery, you can use the click() method to attach a click event handler to the button elements. In the event handler function, you can use the this keyword to refer to the button that was clicked.


Here is an example:

1
2
<button class="btn" id="btn1">Button 1</button>
<button class="btn" id="btn2">Button 2</button>


1
2
3
4
5
6
7
8
9
// Attach click event handler to button elements
$('.btn').click(function() {
  // Determine which button was clicked
  if (this.id === 'btn1') {
    console.log('Button 1 clicked');
  } else if (this.id === 'btn2') {
    console.log('Button 2 clicked');
  }
});


In this example, we first attach a click event handler to all elements with the class btn. In the event handler function, we use the this keyword to refer to the button that was clicked. We can then use the id property of the button to determine which button was clicked and take the appropriate action.