Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add jQuery click handler to multiple elements?

Tags:

jquery

I need to have a for loop inside my jQuery.

Example:

  for(i=0;i<counter;i++)
   {
    $("div"+i+"").click(function(){//some code});
   }

How can I accomplish this?


EDIT:

This code was posted by the OP in a comment to one of the answers:

$("#displayPanel div").click(function (){ alert($(this).attr("id")); } 

<div id="displayPanel" class="displayPanel"> 
  <div id="heading"> Display Panel </div> <br/> 
  <div id="save" class="saveClass"></div> <br/> 
  <div id="field1" class="my"> 
    <label id="labelstr1">Untitled1</label> 
    <input id="inputstr1" type="text"/> 
  </div> 
  <div id="field2" class="my"> 
    <label id="labelstr2">Untitled1</label> 
    <input id="inputstr2" type="text"/> 
  </div> 
</div>

The alert is showing me the id for the first two divs and not for the field1 and field2.


Note:

The Field1 and Field2 divs are created on the fly.

like image 912
useranon Avatar asked Jun 03 '09 10:06

useranon


3 Answers

You can put the divs with a common class

<div id="d1" class="your_css_class your_control_class">
<div id="d2" class="your_css_class your_control_class">
<div id="d3" class="your_css_class your_control_class">
<div id="d4" class="your_css_class your_control_class">
<div id="d5" class="your_css_class your_control_class">

$(".your_control_class").click(function(){
   var div_id=$(this).attr("id"); // gives you the ID of the clicked div
   if(div_id==="d1") functionForDiv1();
   else if(div_id==="d2") functionForDiv2();
   ...
});

EDIT:

If you have everything inside that big div then you can do:

$("#displayPanel > div").click(function(){
...
like image 105
fmsf Avatar answered Sep 29 '22 13:09

fmsf


The loop seems unnecessary since the selector for div will apply to all divs.

$("div").click(function(){
  //this will apply to any div you click on the page
  //for example:
  $(this).css('color','red'); //change the color of the div clicked to red
});

EDIT: Since you mention in the edit that #field1 and #field2 are created on the fly, then you need to use .live() to bind the click event as shown below:

$("#displayPanel div").live('click', function(){
  alert($(this).attr('id'));
});
like image 25
Jose Basilio Avatar answered Sep 29 '22 11:09

Jose Basilio


You can, for example, loop through all div's like this:

$("div").each(function() {
    $(this).hide(); // this points to the current element
});
like image 29
Philippe Leybaert Avatar answered Sep 29 '22 11:09

Philippe Leybaert