Add multiple menu items dynamically to a dropdown menu in TinyMCE, with each menu item directing to the last item clicked when clicked

I'm currently utilizing tinymce along with tinymce-variable. My goal is to create a dropdown menu with dynamic menu items generated from an SQL database. Through a loop, I've managed to successfully create multiple dropdown menus by using editor.addMenuItem() for each menu item.

for(i=0;i<data.length;i++)
{
    template_var    = data[i]['variable'];       
    text_val        = template_var.replace(/\s/g , " ");
    editor.addMenuItem(template_var,
    {
        text    : text_val,
        context : 'newmenu',
        onclick : function ()
        {               
            editor.plugins.variable.addVariable(template_var);
        }
    })
}   

The issue I'm encountering is that when I click on any menu item, it adds the last menu item to the editor instead of the specific menu item I clicked on. It seems like it's overwriting the

editor.plugins.variable.addVariable(template_var);
with the last menu item for all menu items. How can this be possible?

Thank you in advance.

Answer №1

When a menu item is clicked, it goes directly to the specific line of code

editor.plugins.variable.addVariable(template_var);
associated with that menu item. However, when this code is executed in a loop, it only recognizes the last line of the code. This results in clicking on any menu item performing an action only for the last menu item because the code gets overridden by the last item at the end of the loop. To solve this issue, I concatenated the editor.addMenuItem() code for each menu item as a string. Then, I executed that string within the setup :function (editor){} section of the tinymce.init({}) using eval(). By doing this, when we click on a menu item, it can properly recognize and execute the corresponding
editor.plugins.variable.addVariable(template_var);
for that particular menu item.

<script type="text/javascript">
variablenames_concat='';
addmenu_concat      ='';
for(j=0;j<data.length;j++)
        {
            variablenames_concat+=data[j]['variable']+',';
            template_var        =data[j]['variable'];
            text_val            =template_var.replace(/\s/g , " ");//remove underscore
            //string concatenate editor.addMenuItem for each of item 
            addmenu_concat      +='editor.addMenuItem("'+template_var+'",{text  : "'+text_val+'",context: "newmenu",onclick: function (){editor.plugins.variable.addVariable("'+template_var+'");}});';
        }
variablenames_concat = variablenames_concat.replace(/,\s*$/, "");//remove last coma

tinymce.init
({
  selector  : 'textarea',
  height    :  500, 
  plugins   : 'variable',
  menu      :
            {
                newmenu:
                {
                    title : 'Menu', items : variablenames_concat,           
                }
            },
 content_css: 
            [
                '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
                '//www.tinymce.com/css/codepen.min.css'
            ],
content_style:".variable{cursor:default;background-color:#65b9dd;color:#FFF;padding:2px;border-radius:3px;font-weight: bold;font-style:normal;display:inline-block;}",


setup        : function (editor)
                    {
                      eval(addmenu_concat);
                    }
});
</script>

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

Transform User's Regex Output into Uppercase

My nodejs program allows users to input text and apply their own regular expressions for editing. I want users to have the option to capitalize or lowercase text as well. For example, if a user enters "StackOverflow is great!" with the regex (.) set to be ...

Trigger an immediate repaint of a DOM element in the browser

Searching for a way to insert a large HTML markup into a DOM element that will take some time. This is why there's a need to display a preloader indicator before the process begins. Two blocks are involved: #preloader and #container. Initially, the pr ...

Preserve a data point without causing any alterations

I am working with a device that continuously sends values until it is stopped. These values are then saved inside an array. deviceMonitoring( device2 ){ // In this function, I populate the arrayTimestamp and then copy the first value. this.arrayElement = t ...

Running PHP scripts one after the other with ajax requests

This situation has been puzzling me for quite some time now. I have an ajax call set up like this: function update() { $.get("update.php", function(data) { $("#output-progress").html(data); }); } And I trigger it like this: window.se ...

The issue of Undefined TypeError arises when using Angular HttpInterceptor and injecting any service

Issue: I'm facing a problem where I am unable to inject any service into the constructor of my HttpInterceptors. Every service I try to inject results in the error: TypeError: Cannot set property 'authenticationService' of undefined Even ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

Utilizing a JavaScript-sent URL within a PHP data grid: A step-by-step guide

I am working on a JavaScript function that fetches the URL of an API needed for a data grid. This API displays the students assigned to a particular teacher. The data grid must dynamically change based on the user (the teacher initiating the session), and ...

Tips for utilizing the onload attribute alongside the ng-controller directive to run a function that has been established within the controller

When trying to call the submit() function as soon as the page loads, I keep encountering a submit() method not found error. The positioning of ng-controller and onload is confusing to me. If there is an alternate method in Angular to achieve this, please ...

Detecting collisions between two squares in an HTML5 canvas

class Snake { constructor() { this.x = 400; this.y = 400; this.width = 25; this.height = 25; } draw() { ctx.fillRect(this.x, this.y, this.width, this.height); } } let snake = new Snake(); class ...

My Javascript file is not being recognized by MVC

Initially, I created an MVC application without fully understanding that MVC is more backend-oriented than frontend-focused. I ended up building a simple website with just HTML, CSS, and Javascript files, which worked perfectly. However, when I tried to in ...

Disable Three.js when WebGL is not supported: Tips and tricks

I read about how to switch to canvasrenderer if webgl is not supported. renderer = Detector.webgl? new THREE.WebGLRenderer(): new THREE.CanvasRenderer(); I'm not sure how to completely remove everything if webgl is not detected. I have an image in t ...

How to clean a string from PHP code using jQuery

Looking for a solution to extract PHP code from a string. The string I have contains PHP code that needs to be removed. text = '<?php // This is a test sample ?> This is a description'; text.replace(/\<\?.*\?\?\ ...

How should res.render() and res.redirect() be properly utilized within Express framework?

I am struggling to understand the difference between res.render('viewname', {msg: 'Message' }) and res.redirect('route') The render function allows you to pass a "message", but the redirect function does not. However, ther ...

Retrieve a text and save it into a variable

Is there a way to extract a specific string and save it as a variable? For example, if I have the following URL: http://sub.site.com/WordsHere-t.jpg I am looking to extract just WordsHere. The length of this string can vary and will not always be 9 chara ...

Include the particules.js library in an Angular 4 project

I am currently working on integrating Particles.js into my Angular project, but I am facing an issue with the Json file not loading. import { Component, OnInit } from '@angular/core'; import Typed from 'typed.js'; declare var particl ...

Implementation of async operations using while loop in Node.js

I'm facing an issue with my code snippet. Here's what it looks like: Rating.find({user: b}, function(err,rating) { var covariance=0; var standardU=0; var standardV=0; while (rating.length>0){ conso ...

Issues with slow scrolling and sticky sidebar on websites with infinite scrolling feature

My webpage has a sidebar that is supposed to scroll down with the page. However, I am experiencing some lagging issues where the sidebar appears a few seconds after scrolling. Additionally, the sidebar keeps moving downwards, making the page longer and cau ...

Is there a way to showcase an array parameter in a url's format?

Objective Currently, I am developing a project using NextJS 12 and I am facing an issue with passing an array as a parameter to the query. Desired Outcome The expected format for passing the array as a parameter should look like this: /path?address_id=1 ...

Having trouble with smooth scrolling for anchor links?

I need help trouble-shooting a smooth scroll effect issue with anchor links on a client's website. Whenever I add the scroll code, the anchors on the page stop working altogether. I tried creating a pen with just a navigation and the code, and it work ...

Encountering a theme issue in the makeStyles function within Material-UI version 5

While working on some React components, I created a styles.js file for each of them. I am following a YouTube tutorial that uses material-ui version 4, so I decided to upgrade to V5. Code snippet for the component (Form): import React from 'react&apo ...