If I understand your problem well what you want is to escape the HTML tags so you can see the source code this way:
<p class="test">Hello world! </p>.
To do this you have to transform some of the symbols of this HTML string into their corresponding HTML entities.
I suggest you use a library for that like he js.
The code would look like this:
$(function(){
var val = $(".val-input").html(); // aqui tem de ser .html()
var text = he.escape(val); // <- esta é a linha que queres
$("#mostrador").html(text); // aqui tem de ser .html()
});
Option for simple strings:
If strings are simple you can use this code:
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
What the code does is to search the string for characters like &<>"'\/
and replace them in the string by their visual representation in HTML, which is in the object entityMap
.
If the user has just typed, what you have works: http://jsfiddle.net/05cpys6q/
– bfavaretto
If I type some HTML tag inside the contenteditable it will only display the value from within the HTML tag
– David Damasceno
You withdrew the acceptance of the answer. Any errors in the answer? or missing any details?
– Sergio
I tried every way to use the he.js library, but at all times it didn’t work, even though I did exactly as in your example.
– David Damasceno
@Daviddamasceno added another option to answer with example as well. If you want you can make a jsFiddle that reproduces your problem with
he.js
for me to take a look... or else you can put here the code of your page.– Sergio
Okay, thanks @Sergio , now yes it worked. Thanks for the help.
– David Damasceno