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( "<", "<" );</textarea>
On screen this will look like this:
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:
Recent Comments