tinymce update textarea value using jquery

TinyMCE Update Textarea Value using jQuery

As a blogger, I often use TinyMCE editor to write my blog posts. Recently, I wanted to update the value of the textarea in which TinyMCE was initialized using jQuery. After doing some research, I found out that there are multiple ways to do this.

Method 1: Using setContent() Function

The first method to update the value of TinyMCE textarea is by using the setContent() function. This function sets the content of the editor to the specified value. Here's the code:


// Get the TinyMCE instance
var ed = tinymce.get('mytextarea');

// Update the value of the editor
ed.setContent('New content');

In the above code, 'mytextarea' is the ID of the textarea in which TinyMCE was initialized.

Method 2: Using jQuery val() Function

The second method to update the value of TinyMCE textarea is by using the jQuery val() function. This function sets the value of an input field, including textarea. Here's the code:


// Get the textarea element
var textarea = $('#mytextarea');

// Update the value of the textarea
textarea.val('New content');

// Trigger the change event to update TinyMCE content
textarea.trigger('change');

In the above code, 'mytextarea' is the ID of the textarea in which TinyMCE was initialized. The trigger() function is used to update the content of TinyMCE.

Method 3: Using TinyMCE ExecCommand() Function

The third method to update the value of TinyMCE textarea is by using the execCommand() function. This function executes a command in the editor's context. Here's the code:


// Get the TinyMCE instance
var ed = tinymce.get('mytextarea');

// Execute the 'mceSetContent' command to update the content
ed.execCommand('mceSetContent', false, 'New content');

In the above code, 'mytextarea' is the ID of the textarea in which TinyMCE was initialized. The 'mceSetContent' command is used to update the content of TinyMCE.

These are the three methods to update the value of TinyMCE textarea using jQuery. You can choose any of these methods depending on your requirement.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe