views:

27

answers:

2

I have a set of dynamic headings and hidden divs with the idea that when the user clicks on a heading it toggles the div underneath to show/hide

the divs all have an id in the form "div_x" where x is dynamically generated

Ive managed to use .each() to loop over all divs that begin with div_ and I can .split the x portion of the id, but I'm unsure how to get jquery to get each heading to show/hide only the relevant other div

$('#[id^=div_]').each(function(){

    exploded_id = this.id.split("_");
    id = exploded_id[2];

    $("#"+this.id).click(function() {

      $("#div_body_"+id).slideToggle("slow");

   });

});

I'm sure someone will be able to point out the flaw here

+2  A: 

why not use a live function and select using classes? This way you can dynamically add using ajax any number of elements which then take on the same behaviour automatically:

<div id="div_1" class="outer">
   <div class="body">
   </div>
</div>

<div id="div_2" class="outer">
   <div class="body">
   </div>
</div>

<div id="div_3" class="outer">
   <div class="body">
   </div>
</div>

Then use:

$(function () {
    $('.outer').live("click" function () {
      $(this).find('.body').slideToggle("slow");
    });
});
Richard
Your code is fine except for the fact that ids can't be numbers only.
Sarfraz
Thanks, now corrected
Richard
@Richard: And now +1 too :)
Sarfraz
+2  A: 

Your selector is wrong, you don't need the # in front of the attribute-starts-with selector:

$('#[id^=div_]')

Should be either of the following instead:

$('[id^=div_]')
$('div[id^=div_]')

Also, you can apply a click handler to the entire collection, the each() is unnecessary here. For instance:

$('div[id^=div_]').click(function(){
    var id = this.id.split("_").pop();
    $("#div_body_"+id).slideToggle("slow");
});
Andy E
Perfect!!!!!!!!!!!!!!!!!!!!!
Tim