Scorpio
Scorpio

Reputation: 1171

toggle div depending on which one is selected

 var header = $("#accordion");

            $.each(data, function () {
                header.append("<a id='Headanchor' href='javascript:toggleDiv($(this));'>" +   this.LongName + "</a>" + "<br />",
                "<div id='myContent' style='display:none'>" +
                "<ul>" +
                "<li>" + "ID: " + this.Id + "</li>" +
                "<li>" + "Short Name: " + this.ShortName + "</li>" +  "</ul>" + "</div>"
                );


                function toggleDiv(element) {
       var x = element.next();
       x.toggle();

       <div id="accordion">

</div>

working script for just one div i.e. first

function toggleDiv() {

              $("#myContent").toggle();

}

I want to toggle the div's depending on which anchor tag is clicked but not able to do it. If i use the id selector then the first div gets toggled but not rest of them as they get the same id's which is erong..can somone please help me out with this ....

Upvotes: 0

Views: 162

Answers (2)

Viktor S.
Viktor S.

Reputation: 12815

In javascript:toggleDiv($(this)) this is pointing to window, not to an object. See JS fiddle. So change code below:

"<a id='Headanchor' href='javascript:toggleDiv($(this));'>"

to:

"<a id='Headanchor' href='#' onclick='return toggleDiv($(this));'>"

and JS code:

function toggleDiv(element) {
       var x = element.next();
       x.toggle();
       return false;
}

Besides, IDs should be unique and in your code you will have multiple Headanchor elements.

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101604

Hide all, and only show the one you want approach:

$('#accordian>div').hide()      // hide all divs within the accordian
  .find('#selectedId').show();  // then show the one that matches the ID you want

But save yourself the trouble of re-inventing the wheel and use jQueryUI.

Upvotes: 0

Related Questions