Search code examples
javascriptjqueryjquery-ui-contextmenu

Passing attributes from a JQuery-UI-ContextMenu trigger to the menu construct


I am trying to access attributes on the DIV tag that is acting as the trigger for a JQuery-UI Context Menu, but am struggling.

In a school context, I will have the name of a student in the text of the DIV, but I need to also pass through an ID number, perhaps using an HTML5 data-pid arribute, or the DIV's ID if necessary.

I can't access either and would really appreciate some guidance.

I am using the contemporary version 1.12.0 of ContextMenu and JQuery 3.0.0.

Please see below my code. Thanks in advance.

    <div id="TheIDIWantToAccess" data-pid="AnotherWantedVariable" class="hasStudentContextMenu"><p>The inner text which is showing fine using $target.text()</p></div>

    <script type="text/javascript">
    $( document ).ready(function() {
        $("#studentContextMenus").contextmenu({

            delegate: ".hasStudentContextMenu",
            preventContextMenuForPopup: true,
            menu: []
            ,beforeOpen: function(event, ui) {
                var $menu = ui.menu,
                    $target = ui.target;

                $(this).contextmenu("replaceMenu",
                    [
                        {title: "<b>" + $target.text() + "</b>"}
                        ,{title: "Award"
                            ,children: [
                            {title: "1_Point", action: function(event, ui) { alert("1 point awarded: " + $target.text() + " (" + $target.id() + ")");}},
                            {title: "2_Points", action: function(event, ui) { alert();} },
                            ]
                        }
                    ]
                );
            }
            ,select: function(event, ui) {
                //alert("select " + ui.target.attr("id"));
            }
        });
    });
</script>

Solution

  • $target.id() is not a valid jQuery method. Use $target.attr("id") instead. There is also a .data() method.