views:

147

answers:

1

Hi All. I am relatively new to Jquery and JSON and this is my first post here, please bear with me.

I have a JSON menu string with an array of three items (name, url, id - our internal page id number) and the top level navigation builds out fine. I loop through the top level items and call a recursive function to get the sub menus.

What I am trying to do now is in a separate part of the web page, use the JSON menu string to find a top level page (news.aspx, for example) and build out a menu for that page and it's submenu items to show in a left side navigation that only to be displayed on the news pages.

The problem I'm having is this script below works without any Javascript errors, however, it is pulling the top level navigation. The top level navigation is essentially called the same way except the functions are CreateMenu() and CreateMenuRecursive().

Some of the code I'm using here I've gotten from reading other posts on this site, but I haven't found an answer to this. Thanks in advance for any help.

<div id="LeftNavDiv">&nbsp;</div> 

<script type="text/javascript">
$(function(){   
var sidemenuString = CreateSideMenu();
$("#LeftNav").html(sidemenuString);
});

function CreateSideMenu(){
$.get("menu");
var sidenavHTML = new Sys.StringBuilder();
for(var i=0; i < menu.MenuItem.length; i++){
 if(menu.MenuItem[i].id == 'a123456'){
  CreateSideMenuRecursive(menu.MenuItem[i],sidenavHTML);
 }
}
return sidenavHTML.toString();
}

function CreateSideMenuRecursive(item, outputHTML){
if(item.MenuItem == null || item.MenuItem.length == 0)
return;

outputHTML.append("<ul>");
for(var i=0; i < item.MenuItem.length; i++){
 if(item.MenuItem[i].id == CurrentPageID){
  outputHTML.append("<li><a href='" + item.MenuItem[i].url + "'>" + item.MenuItem[i].label + "</a>");
 } 
 CreateSideMenuRecursive(item.MenuItem[i], outputHTML);
 outputHTML.append("</li>");
}
outputHTML.append("</ul>");
}
</script>
A: 

As it turns out, I was making it way too complicated. All I had to do was find the href (news.aspx) from the JSON menu string and get the sub menu . I took what I had above and distilled it down to these few lines of code:

<div id="LeftNavDiv"></div>
<script type="text/javascript">
$(function(){   
var sidemenu = $("a[href$='news.aspx']").next("ul").get();
$("#LeftNavDiv").html(sidemenu);  
});
</script>

It dynamically creates this div and unordered list pulling even the style, i.e., "menu-top" from the JSON menu string:

<div id="LeftNavDiv">
    <ul>
        <li class="menu-top"/>
        <li><a href="sandbox1.aspx">Lorem ipsum</a></li>
        <li class="menu-bot"/>
   </ul>
</div>
Jennifer