jQuery Ui Context menu dereference the id

880 views Asked by At

How can I retreive the ids of contexts menu just like in https://github.com/mar10/jquery-ui-contextmenu/blob/master/README.md, but with additionally provided IDs

<div id="container">
    <div id="menu1" class="hasmenu">AAA</div>
    <div id="menu2" class="hasmenu">AAA</div>
</div>

in the select method?

$("#container").contextmenu({
    delegate: ".hasmenu",
    menu: [
    {title: "Copy", cmd: "copy", uiIcon: "ui-icon-copy"}
    ],
    select: function(event, ui) {
        alert("select " + ui.target.id); // ui.target.id fails!!!
    }
});
2

There are 2 answers

4
blgt On

ui.target is a jQuery element, not a plain javascript HTMLElement. You can get at that with the [0] suffix ($(ui.target)[0].id) or, more readably, just use the jQuery attribute accessor function:

ui.target.attr("id")

Here's a link to a fiddle example and a stack snippet below

$("#container").contextmenu({
    delegate: ".hasmenu",
    menu: [
    {title: "Copy", cmd: "copy", uiIcon: "ui-icon-copy"}
    ],
    select: function(event, ui) {
        alert("select " + ui.target.attr("id"));
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<script src="http://cdn.jsdelivr.net/jquery.ui-contextmenu/1.8.0/jquery.ui-contextmenu.min.js"></script>
<div id="container">
    <div id="menu1" class="hasmenu">AAA</div>
    <div id="menu2" class="hasmenu">AAA</div>
</div>

0
jiten jethva On

Use following code:

$(ui.target).closest('div').attr('id');