Creating a custom context menu using jQuery for dynamically generated elements

Here's the situation: I have a dynamic system that handles div ids. I successfully took control of the context menu with my own script, but it only works if the element id is hardcoded. I've been attempting to create a function that retrieves the element name from an array list, but it keeps throwing errors all over the place.

function menuclick()
{
    alert("Menuclick Called");
    var limen= ["armenu", "ormenu", "prmenu", "apmenu", "auxmenu", "itmenu", "sysmenu"];
    var menues= Array();
    var men1 = "menu$pf1$topmen$topmen$menul$menuli$";
    for (idx=0;idx<6;idx++){
        menues[idx] = "#"+men1+limen[idx];
        $(menues[idx]).bind("contextmenu", this.id, function(e) {
            $('#example-menu').css({
                top: e.pageY+'px',
                left: e.pageX+'px'
            }).show();
        return false;
    });
        alert(menues[idx]);
    }
    return;
}

The issue seems to revolve around $(menues[idx]).bind, specifically the menues[idx] part. I just can't seem to pinpoint why it's causing trouble. Any suggestions?

EDIT ** I forgot to mention, the error message displayed by Firebug reads:

"Uncaught exception: Syntax error, unrecognized expression: $pf1$topmen$topmen$menul$menuli$armenu"

EDIT** It's worth noting that php is used to fetch the div ids from a database.

Answer №1

Ah, the quirks of .NET and its unique conventions. Instead of referencing an "id", you're actually looking for a "name". Your menu code should be structured like this:

<div name="menu$pf1$topmen$topmen$menul$menuli$armenu" id="menu_pf1_topmen_topmen_menul_menuli_armenu"> ... </div>

With that in mind, you have a couple of options to choose from.

  • 1) Replace dollar signs with underscores (the preferred approach)

var men1 = "menu_pf1_topmen_topmen_menul_menuli_";

  • 2) Update the line of code below:

menues[idx] = "#"+men1+limen[idx];

to this:

menues[idx] = "[name='" + men1 + limen[idx] + "']";

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

Error occurred while calling the Javascript webservice

When attempting to call a basic web service and pass an email address as a parameter, I encountered an error message stating "Request format is unrecognized for URL unexpectedly ending in '/IsPreUsedEmail'". Any suggestions on how to resolve thi ...

Unable to simulate default export in the tested document

I am currently working on a Typescript project and facing the challenge of adding tests for functions that are responsible for sorting through MongoDB responses to extract meaningful results. To facilitate this, I have set up an in-memory mock of the datab ...

The $.post function is failing to return a successful response

Utilizing select2 to gather multiple member names in a single input field, I have implemented the following ajax code within my form.php file: $('#student_vgroup').submit(function(event){ event.preventDefault(); var name = $( ...

Parsing JSON data into different data types in C#

I am looking for a way to transfer various types of data from JavaScript to C#. Specifically, I want to send a JSON object from the JavaScript side using an AJAX call. Here is an example: AnObject = new Object; AnObject.value = anyValue; $.ajax({ typ ...

Exploring Sanity npm package with Jest for mocking tests

I am encountering an issue with mocking some code in my sanity.ts file: import sanityClient from '@sanity/client'; // eslint-disable-next-line @typescript-eslint/no-var-requires const blocksToHtml = require('@sanity/block-content-to-html&ap ...

Issues arising from using AJAX with ASP.Net and encountering problems with JavaScript not functioning properly during

I have a scenario where I am using ASP.Net to redirect a page to a download page with the help of AJAX. The redirection is successful, the file is downloaded, and the calling page is displayed as expected. However, I need to execute some JavaScript code af ...

Using Javascript to eliminate divs on a page that have the attribute display:none

Looking for a way to remove generated divs with display: none using JavaScript? Let's find a solution. <div id="workarea"> <div id="message" class="messages" style="display: none;">Your message was saved</div> <div id="message" c ...

Establishing connections to numerous databases using ArangoDB

I am currently developing a product that involves the dynamic creation of a new database for each project, as new teams will be creating new projects based on their specific needs. The backend of the product is built using Node.js, Express.js, TypeScript, ...

Issue with incorporating Material UI HtmlTooltip within Material UI Select MenuItem and handling synthetic events in the select onChange method

---OBJECTIVE--- The goal is to integrate a Material UI select component with MenuItems wrapped in HtmlTooltips, providing hover information for each option in the list. For now, I'm keeping it simple as a proof of concept and plan to implement dynam ...

Scroll horizontally based on mouse movement

My angular directive that enables me to choose the content of table cells is performing as expected. However, I encountered an issue when attempting to select multiple cells at once - the scrollbar does not move, hindering my ability to select the cells. ...

Having trouble with the response from the Object object?

Can someone assist me with the response I am getting here? I am receiving a response from an API call and trying to store the results from screen_results. However, when I attempt to print it out, all I see is [Object object]. I have tried to stringify it, ...

Utilize Bootstrap to deactivate the time picker feature

I recently downloaded an admin template that includes a datetimepicker. However, I only need the date picker and am struggling to disable the time picker. Can anyone help me fix this issue? I will provide my class file, HTML code, and a snapshot of the tim ...

JavaScript - Modify the proposed content prior to inserting it into the input field

In my current project, I have implemented a feature using jQuery UI - v1.11.4, where an HTML textbox utilizes a JavaScript autocomplete functionality. The suggested string for the textbox is created by concatenating several columns (patient_no, patient_nam ...

Creating a new JavaScript object using a Constructor function in Typescript/Angular

Struggling with instantiating an object from an external javascript library in Angular/Typescript development. The constructor function in the javascript library is... var amf = { some declarations etc } amf.Client = function(destination, endpoint, time ...

An issue with Angular $parse arises when attempting to filter or order hash values that begin with numbers

I have encountered a challenging situation with my angular orderBy filter. It works perfectly except when the expression starts with a hash followed by an integer. Check out this fiddle to see the issue in action. The filter structure I'm using look ...

What is the best way to transfer a variable from JavaScript to PHP?

I've been searching through numerous answered topics but I just can't seem to resolve the issue I'm facing. I'm utilizing a bootstrap date-time picker () and my objective is to pass the displayed value from a page containing the calenda ...

The CSS code hides a portion of the fixed side navigation when the main content is shorter than the navigation bar

My side nav and main content are both dynamic. The issue arises when the navigation is longer than the main content, causing its height to be set to the viewport height and the rest is hidden. How can I address this problem without resorting to an unsightl ...

Issue in NextJS: During project build, component props become undefined even though they function properly in development mode

Despite functioning properly in dev mode, a component is throwing an error during the build process. It claims that the 'open' prop is undefined, even though it behaves correctly and outputs the right result when console logged on localhost. cons ...

Navigating PopUpWindows using SeleniumIn this guide, learn the best

I have attempted to manage a particular PopUp / new Window in Java using SeleniumServer, but unfortunately, it is not functioning as expected. Here is what I have tried: selenium.click("css=a[title=\"Some irrelevant title\"] > div.text"); Thr ...

What makes fastify-plugin better than simply calling a regular function?

I recently came across a detailed explanation of how fastify-plugin operates and its functionality. Despite understanding the concept, I am left with a lingering question; what sets it apart from a standard function call without using the .register() metho ...