Bind Multiple Controls to a Single Event in jQuery

In this sample, we will see how to bind Multiple Controls to a single event. We will bind 3 button controls (Button A, C and E) to a single click event. This example also demonstrates how to create an array of controls and loop through them. Here’s how:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Multiple Elements Single Event</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
var btns = $('#btn1,#btn3,#btn5');
$.each(btns, function() {
$(this).click(function() {
alert(this.id);
});
});
});
</script>
</
head>
<
body>
<
input id="btn1" type="button" value="Button A" />
<
input id="btn2" type="button" value="Button B" />
<
input id="btn3" type="button" value="Button C" />
<
input id="btn4" type="button" value="Button D" />
<
input id="btn5" type="button" value="Button E" />
<
input id="btn6" type="button" value="Button F" />
</
body>
</
html>
See a Live Demo here

5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. You don't need to use each for this

    $(function() {
    $('#btn1,#btn3,#btn5').click(function(){
    alert(this.id);
    });
    });

    Also $.each is less efficient than using a plain for loop.

    ReplyDelete
  3. Milos - Thanks for that tip. I wanted to demo how to loop through an array of controls. Anyways what you say is perfectly ok in its own context.

    @FutureReader -- If you have a requirement to iterate through a set of controls, apply a filter and then collect the results in a new array - then intead of a loop, you can use the built in map() function.

    ReplyDelete
  4. I used each at asp.net, there is __dopostback() in each button, the program automatically postback first button, i don't know why. but using $('#btn1,#btn3,#btn5').click(function(){
    everything is fine.
    added by iG4

    ReplyDelete
  5. use e.preventDefault to suppress a postback.

    $(function() {
    $('#btn1,#btn3,#btn5').click(function(e){
    e.preventDefault();
    alert(this.id);
    });
    });

    ReplyDelete