Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery binding click event to multiple buttons

Tags:

I have 3 buttons b1, b2, b3. How to bind click on 3 buttons. Var b1 = $("#b1"); Var b2 = $("#b2");

$(b1,b2).bind("click", function(){});

jsfiddle.net/Xqpaq/

like image 307
user321963 Avatar asked Jul 18 '13 05:07

user321963


Video Answer


2 Answers

you can use .add()

b1.add(b2).add(b3).click(function(){
})

Demo: Fiddle

or use multiple selector

$('#b1, #b2, #b3').click(function(){
})

Demo: Fiddle

like image 118
Arun P Johny Avatar answered Nov 16 '22 14:11

Arun P Johny


I would highly suggest making the button click function a separate function and then bind each button to it

http://jsfiddle.net/Xqpaq/1/

$(document).ready(function(){ 

     var b1 = $("#btn1");
     var b2 = $("#btn2");
     var b3 = $("#btn3");

    var btnClick = function(e){
        alert("Button: "+e.currentTarget.id);
    }

    b1.on('click', btnClick);
    b2.on('click', btnClick);
    b3.on('click', btnClick);

});

The alternative is to use classes instead of ids. Like so:

http://jsfiddle.net/Xqpaq/2/

<input type="button" id="btn1" class="btn-click-action" value="submit"/>
<input type="button" id="btn2" class="btn-click-action" value="submit2"/>
<input type="button" id="btn3" class="btn-click-action" value="submit3"/>

Then JS:

var btnClassClick = function(e){
    alert("Button clicked from class: "+e.currentTarget.id);
}

$('.btn-click-action').on('click', btnClassClick);
like image 28
Kevin Jantzer Avatar answered Nov 16 '22 12:11

Kevin Jantzer