Mastering the Art of Dynamically Passing Data-IDs with JQuery

My custom context menu should inherit the data-id value of the list item that was right-clicked.

Specifically, I have an unordered list of countries. When a user right-clicks on any of these countries (list items), a context menu pops up. The goal is to pass the data-id value to the list items in the context menu.

Upon inspection in the Elements window, it appears that the data is being passed correctly initially. However, when a user clicks on a different country, the data-id still reflects the first country clicked. What could be causing this issue?

This is how the file is structured:

// Code for handling ESC key event,
$(document).bind("keyup", function(event) {
    // If ESC key pressed,
    if (event.keyCode == 27) {
        // Hide Context Menu
        $('.context-menu').hide();
        $('.context-menu').each(function() {
            $(this).find("li").each(function() {
                var current = $(this);
                current.removeAttr("data-id");
            });
        });
    }
});

// On document click event,
$(document).on("click", function() {
    $('.context-menu').hide(); // hide context menu
    $('.context-menu').each(function() {
        $(this).find("li").each(function() {
            var current = $(this);
            current.removeAttr("data-id");
        });
    });
});

$(document).ready(function() {
    $('.members-list').on("contextmenu", "li", function(e) {
        e.preventDefault();

        var id = $(this).data("id");

        $('.context-menu').each(function() {
            $(this).find("li").each(function() {
                $(this).attr("data-id", id);
            });
        })

        $('.context-menu')
            .css({
                top: e.pageY + 'px',
                left: e.pageX + 'px'
            })
            .show();
    });

    $('.context-menu').on("click", "li", function() {
        var id = $(this).data("id");
        var action = $(this).data("action");
        switch (action) {
            case "view":
                alert("View: " + action + " " + id);
                break;
            case "edit":
                alert("Edit: " + action + " " + id);
                break;
            case "delete":
                alert("Delete: " + action + " " + id);
                break;
        }

        // Hide Context Menu
        $('.context-menu').hide();

        // Remove data id
        $('.users-menu').each(function() {
            $(this).find("li").each(function() {
                var current = $(this);
                current.removeAttr("data-id");
            });
        });
    });
});
 *,
 *::before,
 *::after {
     margin: 0;
     padding: 0;
     outline: 0;
 }
 ul,
 ol {
     list-style: none;
 }
 .members-list li {
     color: ghostwhite;
     cursor: pointer;
     display: block;
     background: black;
     padding: 4px;
     margin-bottom: 2px;
 }
 .context-menu {
     display: none;
     padding: 2px;
     position: absolute;
     background: ghostwhite;
 }
 .context-menu li {
     padding: 6px;
     cursor: context-menu;
     border-bottom: 1px solid gray;
 }
 .context-menu li:last-child {
     border-bottom: 0;
 }
 .context-menu li:hover {
     color: ghostwhite;
     background: gray;
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <div class="members">
    <ul class="members-list">
    <li class="member" data-id="south-africa">South Africa</li>
    <li class="member" data-id="england">England</li>
    </ul>
    </div>
    <div class="context-menu">
    <ul class="context-menu-list">
    <li class="context-menu-item" data-action="view">
    <div class="menu-item">
    View Member
    </div>
    </li>
    <li class="context-menu-item" data-action="edit">
    <div class="menu-item">
    Edit Member
    </div>
    </li>
    <li class="context-menu-item" data-action="delete">
    <div class="menu-item">
    Delete Member
    </div>
    </li>
    </ul>
    </div>

I have captured screenshots from the Elements inspector. Please refer to them here: https://i.sstatic.net/HRHJB.png

Answer №1

Greetings! Please make the following substitution:

var id = $(this).data("id"); with var id =$(this).attr("data-id"); 

After adding this adjustment to $('.context-menu').on("click", "li", function()

You can verify it and let me know if any issues arise

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Firefox now recognizes 4-digit hex color codes as rgba values during parsing

Recently, while using Firefox version 49, I accidentally discovered that it parses 4-digit hex colors as rgba. After referring to the CSS specification and searching through MDN, I couldn't find any documentation about this feature. Can anyone provide ...

Tips on creating hyperlinks for each database entityCreating hyperlinks to individual database entities

I have a database table with three columns and four rows. I am looking to add hyperlinks to each entity in the third column of the table and then display the output. When attempting to print the array values, I used the following code: echo "<td>", ...

Challenges with converting JSON into PHP code

I am attempting to output the JSON response below to HTML using PHP. Here is the JSON response : { "data": { "onward": [ { "origin": "LHR", "id": "SB15", "rating": 0, "destination": "FKK", "PricingSolut ...

Tips for utilizing the full feature in velocity.js for activating localscroll

I am currently utilizing velocityjs, localscroll (which is dependent on scrollTo). By default, there is a hidden form on my webpage. I have implemented an anchor tag that, upon clicking, will reveal the form. html <a href="#myForm" class="button" id= ...

What is the best way to set the exact pixel width for a sidebarPanel?

Is there a way to define the precise width of a sidebarPanel in pixels instead of using the width argument? I have found that the width option is not precise enough for my needs. library(shiny) ui <- fluidPage( sidebarLayout( sidebarPanel(widt ...

Leverage Node.js to access an array from app.js within a module

Within my Node app.js file, I am looking to make my array openConnections accessible by the module sse_server.js for the sseStart function. How can I achieve this without necessarily declaring the array as a global variable in app.js? Here is a snippet of ...

Adding a JavaScript global variable into a <div> element within the HTML body

Here is an example HTML tag: <div data-dojo-type="dojox.data.XmlStore" data-dojo-props="url:'http://135.250.70.162:8081/eqmWS/services/eq/Equipment/All/6204/2', label:'text'" data-dojo-id="bookStore3"></div> In ...

The list items are showing incorrect characters when displayed in UTF-8 format

I'm attempting to create a style that will display an arrow in place of the li element. $("html > head").append("<style id=styles>div#panel { position: absolute; border-radius: 3px; font-family:'Arial Black'; font-size:13px; }&bsol ...

Even with the text field populated and clearly existing, Firefox is still throwing a null error when trying to retrieve it using

Hey there! I'm currently working on a sample HTML page and I'm facing an issue with retrieving data from a text field. No matter what I try, I keep encountering the following error: TypeError: document.getElementById(...) is null Let me share t ...

Utilizing float positioning in Responsive Web Design

Attempting to implement a two-column float CSS layout with specific width percentages. My CSS styles for the two columns are as follows: .div1 { width: 25%; float: left; } .div2 { width: 75%; float: right; } .container { width: 960px; } @media scr ...

What's the best way to make sure the footer stays at the bottom of every page using CSS?

Here's the code I've been working on: #footer { font-size: 10px; position:absolute; bottom:0; background:#ffffff; } I'm facing an issue with this code - can anyone offer some assistance? UPDATE: To clarify the issue further: T ...

Passing an ID via Link to retrieve data with getServerSideProps in Next.js

I have several alert components. From each of these components, I aim to pass the itm._id and receive it in [itm].jsx within the same folder. In [itm].jsx, I intend to utilize it in the getServerSideProps function for fetching data. Below is a snippet fro ...

Is it possible to represent a recursive variable using CSS?

When it comes to the html structure: <body> <div> <div> <div> ... </div> </div> </div> </body> Is there a method to create recursive variables that utilize their parent's value: body ...

Capturing radio change events in jQuery: the definitive guide

I'm struggling to capture a simple list of radio buttons. Despite trying various solutions from SO and YouTube, nothing seems to be working for me. Below is the snippet of HTML code: <ul id="shipping_method"> <li> ...

Attempting to output numerical values using Jquery, however instead of integer values, I am met with [Object object]

I am struggling to figure out how to display the value contained in my object after attempting to create a Calendar using Jquery. I attempted to use JSON.toString() on my table data, but it didn't solve the issue. Perhaps I am not placing the toString ...

Is there a way to remove createdAt and updatedAt from every query in Sequelize?

Currently, I am utilizing Node 14 and Sequelize to model an existing Postgres database. The tables that have already been created do not contain the createdAt or updatedAt columns, so my intention is to set up Sequelize in a way that it will never attempt ...

Issue with the functionality of max-height in a CSS grid container

Update: After receiving clarification from @onkar-ruikar, I realized that my original problem was quite misunderstood. While I still haven't figured out how to properly handle the cyclic dependencies issue, I decided to address it separately. As a res ...

Only when the condition is satisfied in AngularJS will I include JSON data

I have a JSON file named components.json containing information about various board spaces: {"components": { "boardSpaces": [ {"name":"GO!", "price":0, "position":0, "type":"go"}, {"name":"Mediterranean Avenue", "type": "property", "pr ...

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

Attempting to develop a versatile and reusable function to handle a variety of statuses

I've implemented a function in my component that filters records based on a specific status and then displays the count of those records on the screen. {props.locations.filter(x => x.details && x.details.status === "NEVER").length} Currently, the ...