0

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!!!
    }
});
T J
  • 42,762
  • 13
  • 83
  • 138
Stefan
  • 137
  • 13

2 Answers2

2

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>
blgt
  • 8,135
  • 1
  • 25
  • 28
  • Just beaten me to it... :) – T J Nov 28 '14 at 16:20
  • @TJ completely offtopic: is there a FAQ page about the stack snippets? I tried to add one here, but can't seem to figure it out, or find a tutorial – blgt Nov 28 '14 at 16:22
  • I'm only aware of [this](http://blog.stackoverflow.com/2014/09/introducing-runnable-javascript-css-and-html-code-snippets/) and [this](http://meta.stackoverflow.com/questions/269753/feedback-requested-runnable-code-snippets-in-questions-and-answers) Maybe I can help you if you're having a particular issue because this contextmenu thingy is [working for me in snippet](http://stackoverflow.com/a/26575857/2333214)... – T J Nov 28 '14 at 16:25
  • Thanks, I had completely missed the "add libraries" button (which just inserted a ``..) – blgt Nov 28 '14 at 16:31
0

Use following code:

$(ui.target).closest('div').attr('id');
Dominique
  • 16,450
  • 15
  • 56
  • 112
jiten jethva
  • 96
  • 1
  • 5