Home / Questions / Using jQuery, what is the approach to attaching a single event handler function to two buttons that have unique IDs,
Explanatory Question

Using jQuery, what is the approach to attaching a single event handler function to two buttons that have unique IDs,

👁 244 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation

To make both buttons trigger the same event when clicked, you can give them the same class and use the class selector instead of the ID selector in your jQuery code.

For example, suppose you have two buttons with IDs "button1" and "button2" that you want to trigger the same event. You can give them both the class "submit-button" like this:


<button id="button1" class="submit-button">Submit</button>
<button id="button2" class="submit-button">Submit</button>

Then you can use the class selector .submit-button in your jQuery code to bind the click event handler to both buttons:


$('.submit-button').click(function(event) {
  // Your event handler code here
});

Now when either button is clicked, the event handler function will be called.