Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get attribute info from a JQuery UI menu select event

Tags:

jquery

I'm trying to get custom attribute from a JQuery UI menu select event. I get undefined when I try doing the script below.

$( "#menu" ).menu({  
select: function( event, ui ) { alert(ui.item.attr("tag")); }
});      

Html

<ul id="menu" style="position:absolute;">
<li><a href="#" tag="something">Aberdeen</a></li>
<li><a href="#" tag="some">Ada</a></li>
<li><a href="#" tag="something1">Adamsville</a></li>
<li><a href="#" tag="something2">Addyston</a></li></ul>

Thank you.

Update: added full code in case I'm linking wrong, I'm new to jQuery. I tried wrapping with $(document).ready as recommended but still getting undefined

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
  $(document).ready(function(){

        $( "#menu" ).menu({  
            select: function( event, ui ) { alert(ui.item.attr("tag")); }
        });      
  });   

</script>
</head>
<body>    
<ul id="menu" style="position:absolute;">
<li><a href="#" tag="something">Aberdeen</a></li>
<li><a href="#" tag="some">Ada</a></li>
<li><a href="#" tag="something1">Adamsville</a></li>
<li><a href="#" tag="something2">Addyston</a></li></ul>
</body>
</html>
like image 390
user1983108 Avatar asked Jan 16 '13 10:01

user1983108


2 Answers

The element returned in the "ui.item" jquery object is the li element (in your example). What you need to do is get it's child element (the a tag) to access the attribute and extract the value of the tag:

var menu = $('#menu');
$(document).ready(function(){
    menu.menu({
        select: function(event, ui) {
            alert(ui.item.children().attr('tag'));
        }
    });
});

http://jsfiddle.net/4bY7d/88/

like image 153
mbaylis Avatar answered Nov 08 '22 21:11

mbaylis


try to wrap inside document.ready

$(document).ready(function(){

      $( "#menu" ).menu({  
          select: function( event, ui ) { alert(ui.item.attr("tag")); }
      });      
});  
like image 33
Kanishka Panamaldeniya Avatar answered Nov 08 '22 21:11

Kanishka Panamaldeniya