UI_Dev
UI_Dev

Reputation: 3417

How to use single click event for multiple button id in jquery

Here I am having two buttons with id frm_submit1 and frm_submit2

<button type="button" id="frm_submit1">Click Me 1!</button>
<button type="button" id="frm_submit2">Click Me 2!</button>

In jquery, I need to do same onclick event for both the buttons. For one button (frm_submit1) click, I used like below. How can I use for multiple buttons?

$(document).on('click', '#frm_submit1', function(event) {
});

I used this, but didn't worked! Any idea?

$("#frm_submit1, #frm_submit2").click(function (e) {  
// do something  
});

Upvotes: 1

Views: 4939

Answers (3)

Jordan
Jordan

Reputation: 79

It's better for this case to use class :

$(".classForButtons").click(function () {  
        // do something  
   });

Upvotes: 1

user2952238
user2952238

Reputation: 787

Try to use the button element as the selector instead. That will run on click on all buttons. Best would be do declare a class on the buttons that you want to use it on and then use the class as the selector instead.

$("button").click(function (e) {  
    // do something  
});

Upvotes: -3

j08691
j08691

Reputation: 207901

Just separate the IDs by a comma:

$(document).on('click', '#frm_submit1, #frm_submit2', function(event) {
});

jsFiddle example

Upvotes: 6

Related Questions