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?
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.
The Field1 and Field2 divs are created on the fly.
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(){
...
                        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'));
});
                        You can, for example, loop through all div's like this:
$("div").each(function() {
    $(this).hide(); // this points to the current element
});
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With