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

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

5 comments:

MiloŇ° said...
This comment has been removed by the author.
MiloŇ° said...

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.

Suprotim Agarwal said...

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.

Anonymous said...

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

Suprotim Agarwal said...

use e.preventDefault to suppress a postback.

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