How to prevent a textarea element from decoding html entities

Today I came across a rather strange problem. I needed a textarea that displayed both html entities as well as html-tags. The problem is, if you display html-entities between textarea-tags, in your browser they are automatically converted to HTML!

An example of the problem of a textarea decoding html-entities

Lets say I have the following HTML-code:

<textarea>replace( "&lt;", "<" );</textarea>

On screen this will look like this:

entities decoded

But since I use the textarea as a sort of a code editor, I really need the “&lt;” to look like “&lt;”, and not like “<".

How to stop a textarea from decoding html entities

We could try something with replace, but for sure I will forget about some entity, and we’d probably get in trouble with “&”-signs that should stay in there, for example in URL’s.

My proposed solution is simple, use Javascript to do an Ajax-call after the page is loaded to fetch the content for the textarea, and place the content in the textarea from Javascript.

Let say I serve the troubled content containing the html tags and the html-entites from a seperate URL, for example “url-with-the-troubled-content.php”.

Now I can get that content using Javascript, in this example some jQuery, and place it in the textarea:

request = $.ajax
	type: "GET",
	url: "url-with-the-troubled-content.php",		    
	success: function(data)
		document.getElementById('id-of-text-area').value = data; 	

The html-entities aren’t converted, and the problem is solved:

entities decoding prevented!


Living in Europe as a freelance programmer. Interested in programming in general, web development and machine learning in particular. Currently most used language is PHP, also experienced in JAVA.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>