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




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 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);
});
});