views:

21

answers:

2

Hi guys,

I have a list that is being fed in to my page using an ASP.NET repeaters. The repeater contains a div (divContainer) with two divs (divTitle and divDetails) inside it. I'm hiding the divDetails and only want to show it if the user click on divTitle.

This works fine for me when in the first divContainer but all subsequent ones that get generated do not work or will slide down the first divDetails. I'm assuming this is because all the elements that get generated by the repeater have the same ID so it selects the first one. I probably need to look for child elements only or something like that but am struggling to get it working.

Here's the HTML:

<div id="divContainer">
    <div id="divTitle">Foo</div>
    <div id="divDetails" class="display:none">Foo details</div>
</div>

<div id="divContainer">
    <div id="divTitle">Foo</div>
    <div id="divDetails" class="display:none">Foo details</div>
</div>

What would the JQuery script be to show the correct divDetails when divTitle withing the same divContainer is clicked?

Thanks for your help.

+1  A: 

Give them classes (IDs have to be unique...the root of your issue), like this:

<div class="divContainer">
    <div class="divTitle">Foo</div>
    <div class="divDetails" style="display:none">Foo details</div>
</div>

Then find the element relatively, via .find() or .children() in this case:

$(".divContainer").click(function() {
  $(this).find(".divDetails").toggle();
});

Here I'm toggling it open/closed, you could also use .slideToggle() for an animation or just .show() if you want it shown only, not toggle-able to hide it again.

Nick Craver
you mean style, not class right?
brendan
@brendan - good catch, didn't see that in the original question code, updated :)
Nick Craver
Good point on not using ID there and using class. That worked great. Thanks!
markiyanm
+1  A: 

Demo

http://jsfiddle.net/Sfna4/

<div class="divContainer">
    <div class="divTitle">Moo</div>
    <div class="divDetails" style="display:none">Moo details</div>
</div>

<div class="divContainer">
    <div class="divTitle">Foo</div>
    <div class="divDetails" style="display:none">Foo details</div>
</div>
​


jQuery(function(){
    jQuery('.divTitle').bind('click',function(){
                  jQuery(this).siblings('.divDetails').slideToggle();
    });  
});
​
Praveen Prasad
This worked also. Thanks Praveen.
markiyanm
You should not use the same ID more than once! (You have 2 `id="divContainer"` s)
Peter Ajtai
@peter- you are right, just fixed that thing. it was just typo mistake
Praveen Prasad