Solved

Modify ASP.NET Menu value using Javascript

Posted on 2013-01-31
11
1,092 Views
Last Modified: 2013-02-02
In a test setup, I've got a user control on a page.  There's a menu on the UC.  The menu is set up in code-behind.  The menu items fire JavaScript functions.  All works fine.  Now I want modify a menu item value in JavaScript, basically to toggle from "Show", to "Hide".  

As shown in the attached image, ASP.NET turns the menu into a div and ordered list, with the div id = Menu1_Menu2 and the list items not seeming to have id's.

Question:  What JS instructions can be used to:
1) get the object representing the menu
2) parse through that object looking for a specific menu item
3) modify that menu item's value

I'm pretty sure I can put the necessary code together if I know the types of instructions above to use.

Any help with this would be appreciated.

Thanks!image of page source
===========The UC =========

<script type="text/javascript"  src="MenuTestzJS.js"></script>

<asp:Menu ID="Menu2" runat="server"
Orientation="Horizontal"
DisappearAfter="250"
MaximumDynamicDisplayLevels="3"
StaticDisplayLevels="1">
<DataBindings>
<asp:MenuItemBinding DataMember="menuitem" NavigateUrlField="url"
TextField="Text" ValueField="Text" />
<asp:MenuItemBinding DataMember="submenuitem" NavigateUrlField="url"
TextField="Text" ValueField="Text" />
</DataBindings>
</asp:Menu>

=========  The XML File =================

<?xml version="1.0" encoding="utf-8" ?>
<Home>
  <menuitem Text="Info" url="javascript:alert('info');">Info</menuitem>
  <menuitem Text="Map" url="">
    <submenuitem Text="Show" url="javascript: alert('showmap');"/>
    <submenuitem Text="Home" url="javascript: alert('map home');"/>
    <submenuitem Text="Map/List" url="javascript: alert('map/list');"/>
  </menuitem>
    <menuitem Text="List" url="">
      <submenuitem Text="Show" id ="List.Show" url="javascript: SwapShowHide();"/>
      <submenuitem Text="Home" id="List.Home" url="javascript: alert('list home');"/>
  </menuitem>
  <menuitem Text="Disc" url="">
    <submenuitem Text="Show" url="javascript: alert('show list');"/>
    <submenuitem Text="Home" url="javascript: alert('list home');"/>
  </menuitem>
</Home>
0
Comment
Question by:codequest
  • 6
  • 5
11 Comments
 
LVL 41

Expert Comment

by:guru_sami
Comment Utility
Give a class name to your menu like:
<asp:Menu ID="Menu2" runat="server" CssClass="mymenu".....

Open in new window

then you can use something like this in jquery:

$("div.mymenu ul li").click(function () {
               alert($(this).find('a').text());
});

Open in new window


You can make use of the 'dynamic' and 'static' classes added by asp.net.
0
 
LVL 2

Author Comment

by:codequest
Comment Utility
Thanks for the input.  At this time I'm not using JQuery.  (Maybe I'll ask a question about that!)  Any way to translate your suggestion into native Javascript?  

Also, I see that that your suggestion would change the navigationUrl js function;  what could be used to change the display value of the menu item?  Referencing some property of the li?
0
 
LVL 41

Expert Comment

by:guru_sami
Comment Utility
Any reason for not using jquery?
just addvthis line of code and you should be all set:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
0
 
LVL 2

Author Comment

by:codequest
Comment Utility
"Any reason for not using jquery?"  

No, but I'm going to keep looking for one :-)

>  Would delay postback <== only the first one, and not much
>  Too heavy for smart phones  <== not so, ditto above
>  I would need to convert all my existing native JS <== only if I want to, and over time
>  I SHOULD convert all my existing JS <== only when I run into browser compatibility issues
>  Have to learn a whole new technology <== probably a very good thing in this case,

Ok, I'll give it a try.   I may come back for more specifics on the menu question, though.

Thanks!
0
 
LVL 2

Author Comment

by:codequest
Comment Utility
guru_sami:  so, next question on your suggested solution;  it would seem that to "get" a specific menu item I would need to add a unique class to each menu item, which means that I would have lots of unique class names, or that I would use up the class attribute as just an identifier.   That has issues either way.  Is there no other way besides the class attribute to "get" a single menu item, and then change it's attribute value?
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 41

Expert Comment

by:guru_sami
Comment Utility
You don't have to add class to each single item...just the main parent asp.net Menu.
The classname is just an identifier to get the parent div.
Again it's not necessary but the simplest way, you can get it using Menu ID. Let me see if I can pull up an eg. for you.

Here's if you don't want to use class on the menu to identify it.
This code goes in page or UC where you have your main menu:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
    $("[id$='Menu2'] li").click(function () {
        alert($(this).find('a').text());
    });
</script>

Open in new window

0
 
LVL 2

Author Comment

by:codequest
Comment Utility
guru_sami:  In looking through the rendered html, it looks like I could search for the "a" element in the "li", and then check the "href" attribute for a unique string value in the JS function argument  and then inspect and modify the "a" element "innerText" attribute (using JQuery equivalent of "innerText") and "href" attribute.

<a tabIndex="-1" class="level2 dynamic" href="javascript: CallMenuRouter('specific_menu_item_argument_5');">Show</a>

So, JQ might be
1)  Get the parent div of the menu, and the "a" elements from the div
2)  Traverse the "a" elements, comparing the href attributes to the target value
3)  On finding the "a" element I'm looking for, update the href attribute and the text value

So, since I'm brand new to JQ, I'm hoping you could provide the basic JQ statements needed for these steps.

Thanks!
0
 
LVL 41

Accepted Solution

by:
guru_sami earned 500 total points
Comment Utility
Here's to get all a's in your menu and loop through it and get the text and href
$("[id$='Menu2'] a").each(function () {
            alert($(this).text());
            alert($(this).attr('href'));
        });

Open in new window

0
 
LVL 2

Author Comment

by:codequest
Comment Utility
Yay!  This works.   I've got to get it to toggle but that should not be a problem.

function SwapShowHide() {
    $("[id$='Menu1_Menu2'] a").each(function () {
        if ($(this).attr('href')) {
            if ($(this).attr('href').indexOf("List.Show") != -1) {
                $(this).text("Hide")
            }
        }
    });
}

One last question, if possible:  in the test, when the item value is changed, it's changed immediately, before the popup sub-menu disappears, so it's seen right then. Can you think of a way to have the sub-menu pop-up collapse BEFORE the change is made?  Or would that happen normally when I put the "some menu function" (the reason for clicking on the menu item) before changing the menu value?

Thanks!
0
 
LVL 41

Expert Comment

by:guru_sami
Comment Utility
On what and all element you want to call SwapShowHide?
I am not much sure if how this will really work in your case but try something like this:

if ($(this).attr('href').indexOf("List.Show") != -1) {
     $(this).mouseout(function () {
                            $(this).text("Hide");
                        });
}

Open in new window

0
 
LVL 2

Author Comment

by:codequest
Comment Utility
Thanks for the input.  That last idea did not work because the mouseout doesn't occur before the "Hide" is changed.  However, everything else has been a huge help, and I'm going to make that last question a separate problem.  

Many thanks!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction This article shows how to use the open source plupload control to upload multiple images. The images are resized on the client side before uploading and the upload is done in chunks. Background I had to provide a way for user…
Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now