When incorporating TinyMCE-editor dynamically into a textarea, it disrupts existing instances

My HTML page consists of text areas with TinyMCE-editors added to them using

tinyMCE.init({mode : "textareas", etc...});
. Initially, everything works smoothly. However, I have a button that dynamically adds a new textarea to the page via AJAX. Upon receiving and appending the response text to a specific div on the page, I attempt to add a new TinyMCE editor to the newly created textarea by executing:

tinyMCE.execCommand("mceAddControl", false, "text" + cnt);

Here, cnt acts as an offset value, making "text" + cnt unique for each textarea.

The issue arises when this process causes all previously existing TinyMCE editors to become blank and unresponsive to any input. Subsequent additions of textareas result in only the newest textarea having a functional editor while the rest are rendered dysfunctional.

I attempted initializing the TinyMCE editors for the initial text areas separately using

tinyMCE.init({mode : "none", etc...});
followed by adding controls individually using
tinyMCE.execCommand("mceAddControl", false, "text" + cnt);
, but encountered the same problem.

Even re-initializing tinyMCE.init({...}) for every new textarea did not resolve the issue, leaving me increasingly frustrated and desperate for a solution...

Answer №1

After troubleshooting, I identified the issue. The error occurred when I merged the responseText from the AJAX call, which generates input fields, with the existing div containing other input fields. By creating a new div and placing each textarea with a tinyMCE editor in its own container, I successfully resolved the problem.

Answer №2

Dealing with a similar issue, I found a solution that worked for me:

Whenever a new textarea was dynamically added, it required the addition of mceAddControl after being inserted into the page. To achieve this, in the JavaScript code responsible for appending the new text area for TinyMCE, I included the following snippet:

$('.editor').each(function(){
    tinyMCE.execCommand('mceAddControl',false,$(this).attr('id'))
  });

Here, editor represents the class assigned to my TinyMCE text areas.

Answer №3

Issue Resolved:

If you are dynamically adding a new textarea element using jQuery, you can incorporate the following function:

initializeTinyMCE();

function initializeTinyMCE(){
  // Initialization
  tinymce.init({
    selector: "textarea",
}

Answer №4

I remember facing a comparable issue in the past... you may find some solutions in this particular discussion

Answer №5

I encountered the same issue and ended up wasting countless hours trying to solve it. While rael_kid managed to find a solution, I want to share my approach for anyone else dealing with this problem.

The problem stemmed from how I was adding dynamic content:

currentDiv.innerHtml += newContent;

This action caused the entire innerHTML to be redrawn, which in turn disrupted the existing tinymce editors. To prevent this issue, it is crucial to use insertAdjacentHTML instead, like so:

currentDiv.insertAdjacentHTML('beforeend', newContent);

I hope this tip helps save someone else from the frustration and time I experienced!

Answer №6

insert the entire initialization code after

$(wrapper).append('write your fields row div or tr code here');
//everything is working perfectly :)

tinyMCE.init({
    mode : "textareas",
    theme : "advanced",
        editor_selector : "mceEditor",
        editor_deselector : "mceNoEditor",  
    theme_advanced_buttons1 : "code,bold,italic,underline,image,separator,strikethrough,justifyleft,justifycenter,justifyright, justifyfull,bullist,numlist,undo,redo,link,unlink,|,tiny_mce_wiris_formulaEditor,tiny_mce_wiris_CAS,|,fullscreen,jbimages",
    theme_advanced_buttons2 : "",
    theme_advanced_buttons3 : "",
    theme_advanced_toolbar_location : "top",
    theme_advanced_toolbar_align : "left",
    theme_advanced_statusbar_location : "bottom",
    plugins : 'inlinepopups,tiny_mce_wiris,jbimages',
    setup : function(ed) {
        // Add a custom button
        ed.addButton('mybutton', {
            title : 'My button',
            image : 'img/example.gif',
            onclick : function() {
                // Add you own code to execute something on click
                ed.focus();
                ed.selection.setContent('Hello world!');
            }
        });
    }
});

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

Tips on changing the arrangement of a set of objects

I'm currently working with an array of objects that I need to restructure into a new array. Despite my efforts, I haven't quite achieved the desired outcome. The initial data I have is organized as follows: data = Team > Days > Games Thi ...

The JavaScript code appears to have malfunctioned as it abruptly terminates with an exit code of 1

When running the code, it reports that prompt-sync cannot be found and exits with error code 1 const input = require('prompt-sync')(); var firstName = input("Enter your first name:"); var lastName = input("Enter your last name:"); console.log(" ...

Issues with External JavaScript Functionality in MVC 4

To better illustrate my issue, I have created a sample code snippet that showcases the problem. Here is the original code used in the view: @model MyProject.Web.UI.ViewModels.MyModel @{ ViewBag.Title = "Test"; } @section scripts{ <script> ...

Retrieve user information from Auth0 once the user has completed the signup process

I am looking to integrate the ability to create new users on Auth0 through my admin panel. Currently, I am utilizing Auth0 lock for signups, but now I need to store these users in my Database, which requires their email and Auth0 user ID. I am exploring o ...

Adding a CSS class to a Vue component with a custom prop

I am looking to create a custom component in Vue that has the following props: text = the text to display in the link. icon = the identifier of the icon to display next to the link. < sidebar-link text="Home" icon="fa-home"> Below is the .Vue ...

jqGrid is throwing an error: undefined is not recognized as a function

Currently, I am in the process of trying to display a basic grid on the screen. Following the instructions provided in the jqGrid wiki, I have linked and created scripts for the required files. One essential css file, jquery-ui-1.8.18.custom.css, was missi ...

What is the best way to display a template after submitting data via AJAX in the Flask framework?

Encountering an issue where I am unable to open render_template after posting data with ajax. Below is my ajax code: if ($(this).attr("value") == "button-three") { var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'neg ...

Efficiently capturing the time elapsed between two occurrences using jquery

After pondering over this throughout the entire day, I feel like I may have lost track and am unable to find a solution on my own. To provide some context: the script I'm working with (shown below) continuously displays the word "WORD" with a quick f ...

The integration of Tailwind merge is experiencing issues when used with CSS modules

My Next.js project utilizes Tailwind for styling elements, and I rely on Tailwind's merge feature to address class precedence issues within my components. It appears that the merge feature does not function correctly when working with CSS modules (spe ...

An issue encountered with getServerSideProps in NextJS 12 is causing a HttpError stating that cookies are not iterable, leading

Currently, I have an application running smoothly on my localhost. However, when it comes to production, an unexpected error has popped up: Error: HttpError: cookies is not iterable at handleError (/usr/src/.next/server/chunks/6830.js:163:11) at sendReques ...

Transmitting various pieces of information using AJAX

Is it possible to send both "credit_uri" and "address" strings in one AJAX request? Currently, only the second string is being sent. How can I include both in the data of the request? $.ajax({ url: '#{add_cards_path}', type: 'POST&apo ...

What is the reason why certain variables in req.body can be read by Express.js while others cannot?

Currently, I am not utilizing body-parser and it is clear that I need to incorporate it. My query pertains to the inconsistency in how my variables are being accessed through req.body without body-parser. Some of the variables display undefined values whil ...

Storing Data with expressjs/session in NodeJS

My development project involves 3 files: app.js, index.js (routes), and Users.js (controller). Upon successful user login (verification between POST data and the database), I aim to store information in a session using expressjs/session. Below is how I c ...

Participant joins in the game table and reacts

I am looking to set up a table where players can join and have their usernames displayed at the bottom of the screen just like in other games. How can I achieve this? export const GameStart = (props) => { const params = useParams(); const gameID = p ...

tips for effectively coordinating functions with promises in node.js

Hey there! I'm currently working on synchronizing my functions by converting callbacks to promises. My goal is to add the post.authorName field to all posts using a forEach loop and querying the user collection. Initially, I attempted to use callb ...

The execution halts after the dispatchEvents function is invoked

After exporting the canvas image, I am facing an issue where the execution stops right after calling pom.dispatchEvent(e);. The following line of code to set the image on the webpage is not getting executed. $("#Digital").attr("src", &a ...

Encountering issues with Node.js and Socket.io not displaying results on Internet Explorer when using a secure connection

I have successfully integrated socket.io, node.js, and express to serve real-time json data to multiple browsers except for IE (tested on version 9) over a secure connection. Everything was functioning smoothly until I switched to HTTPS. From the server&ap ...

Creating a Bottom-Up Menu in React Native: A Step-By-Step Guide

Need help figuring out how to create a menu that pops up from the bottom when a button is clicked. Any advice on where to start? If you have any guidance or insights, they would be highly appreciated. ...

Using the JSON stream object to loop through jQuery with the .each() method

CODE SNIPPET var IMController = { listIM: function () { var params = getUrlVars($("#getIM").attr("href")); $.ajax({ url: "listIM", type: "POST", dataType: "json", data: $.extend(params, { ...

Conceal a TextBox by selecting a checkbox server control in ASP.NET/C# with the assistance of Jquery or Javascript

I've been attempting to dynamically hide and show a Textbox based on the state of a Checkbox. Here is the relevant source code: <asp:CheckBox ID="ShortStoryCheckBox" runat="server" /> <asp:TextBox ID="LeadTextBox" runat="server" Height="7 ...