John Mwaniki /   08 Jul 2023

[Solved]: TinyMCE submitting an empty value

If you are using TinyMCE for rich text editing in your HTML forms, you will most likely (or already have) experience a scenario where on submitting the form with Ajax, the value of the input field integrated with TinyMCE is found to be empty.

This is despite being very sure that content was added to the editor before submitting the form.

Another instance is when the editor is prefilled with content when loading the page or dynamically via Ajax, but after editing the content it remains the same when submitted without reflecting the changes made.

To fix this problem, all you will need is to add this line tinymce.triggerSave() in your JS code before submitting the form.

Example

$("#productForm").submit(function(e){
   tinymce.triggerSave();
   //Your other code
});

When we integrate TinyMCE on a textarea, the editor iframe is shown in place of the original textarea which is hidden. When tinymce.triggerSave() is executed, it moves the HTML content from the editor iframe to the original textarea/form element (that is hidden).

Alternatively, you can add the code below to your TinyMCE initialization code.

setup: function (editor) {
    editor.on('change', function () {
        editor.save();
    });
}

Example

tinymce.init({
  selector: '#myTextarea',
  setup: function (editor) {
    editor.on('change', function () {
        editor.save();
    });
  }
});

The editor.save() line can be used interchangeably with tinymce.triggerSave() as they perform the same action.

The above code ensures that every time a change is made to the content in the editor, editor.save() is executed, and in turn the HTML content in the editor is saved to the original textarea.

This method will work as long as some change is made or anything is typed in the editor.

If you use this (second) method and are adding content dynamically into the editor via Ajax, then you must add tinymce.triggerSave() after updating the editor content or else its value will be blank if you submit without editing it.

Example

tinymce.get('myTextarea').setContent("<p>Hello World!</p>");
tinymce.triggerSave();

That's it!

By following this article, you will be able to fix the issue with the TinyMCE editor submitting an empty value or content that's not updated after editing it.

It's my hope that you enjoyed the article and found it helpful.