I have a dynamically generated menu (C#), like this:
MenuItem(string text, string value, string imageUrl, string navigateUrl, string target)
MenuItem AdminLevel1 = new MenuItem("Admin", "Admin");
MenuItem AdminPedidosRegisto = new MenuItem("Questions", "AdminQ");
NavigationMenu.Items.Add(new MenuItem("Messages Received", "AdminMessagesR", "", "./Admin/Messages.ascx", "ContainerIframe"));
AdminPedidosRegisto.ChildItems.Add(new MenuItem("Pending", "AdminPending", "", "./Admin/Pedidos.ascx", "ContainerIframe"));`
Where ContainerIframe
is the iframe's ID and NavigationMenu
is the (asp:Menu)'s ID.
I want to set some JavaScript to be executed when I click a MenuItem.
Is there a way?
Try putting the following code inside head tag of your .aspx page:
<script type="text/javascript"> window.onload = function(){
var menuTable = document.getElementById("<%=Menu1.ClientID%>"); //specify your menu id instead of Menu1 var menuLinks = menuTable.getElementsByTagName("a");
for(i=0;i<menuLinks.length;i++)
{
menuLinks[i].onclick = function(){return confirm("u sure to postback?");}
}
setOnClickForNextLevelMenuItems(menuTable.nextSibling); } function setOnClickForNextLevelMenuItems(currentMenuItemsContainer){
var id = currentMenuItemsContainer.id;
var len = id.length;
if(id != null && typeof(id) != "undefined" && id.substring(0,4) == "Menu" && id.substring(parseInt(len)-5,parseInt(len)) == "Items")
{
var subMenuLinks = currentMenuItemsContainer.getElementsByTagName("a");
for(i=0;i<subMenuLinks.length;i++)
{
subMenuLinks[i].onclick = function(){return confirm("u sure to postback?");}
}
setOnClickForNextLevelMenuItems(currentMenuItemsContainer.nextSibling);
} } </script>
Note that you do not need to write any code in code behind file for this solution to work. I've tested the code in IE7 & FF2.0
Hope it works for you.
cheers!!