How to set data to TinyMCE text editor

TinyMCE

Share


In this tutorial we will learn to set data to a TinyMCE text editor.

Requirement

We will need the following items.

  • Text Editor like SublimeText, TextMate, Coda, NotePad++ or IDE like Eclipse
  • Web Browser like Chrome or Firefox
  • TinyMCE
  • jQuery

Assumption

It is assumed that you have TinyMCE setup done. To know more about TinyMCE setup check this tutorial.

So lets get started...

The project folder structure will look something like the following...


tinymce
 |
 +--js
 |  |
 |  +-- jquery.min.js
 |
 +--plugin
 |  |
 |  +--tinymce
 |     |
 |     +-- some folders
 |     |
 |     +-- init-tinymce.js
 |     |
 |     +-- tinymce.min.js
 |
 +-- index.html

Step 1: Create files

Create setdata.html file inside the tinymce project folder.

Create setdata.js file inside the js folder. This file will contain the javascript code that we are going to write.

Now the project folder will look like the following...


tinymce
 |
 +--js
 |  |
 |  +-- jquery.min.js
 |  |
 |  +-- setdata.js
 |
 +--plugin
 |  |
 |  +--tinymce
 |     |
 |     +-- some folders
 |     |
 |     +-- init-tinymce.js
 |     |
 |     +-- tinymce.min.js
 |
 +-- index.html
 |
 +-- setdata.html

Step 2: Code

Open setdata.html file and write the following code.


<!DOCTYPE html>
<html>
	<head>
		<title>TinyMCE - Set Data</title>
	</head>
	<body>

		<button id="set-data-btn" >Set Data</button>

		<form id="form-data" method="post">

			<textarea class="tinymce" id="texteditor"></textarea>
			<input type="submit" value="View Data">

		</form>

		<div id="data-container">
		</div>

		<!-- javascript -->
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="plugin/tinymce/tinymce.min.js"></script>
		<script type="text/javascript" src="plugin/tinymce/init-tinymce.js"></script>
		<script type="text/javascript" src="js/setdata.js"></script>
	</body>
</html>

Open setdata.js file and write the following code.


$(document).ready(function(){

	$("#form-data").submit(function(e){

		var content = tinymce.get("texteditor").getContent();

		$("#data-container").html(content);

		return false;

	});

	$("#set-data-btn").on("click", function(e) {
		
		var content = "<p>Hello World</p>";

		tinymce.get("texteditor").setContent(content);

	});

});

Output

Recently Added