JDelage
JDelage

Reputation: 13672

How to allow user to edit formatted text inside an HTML tag?

I am building an app where I would like users to be able to review an existing string in a <p></p> element, mouseover on the text to edit it, and see the edited version when they mouseout.

Right now I am doing that in Javascript replacing the <p> with <textarea>. I populate the <textarea> by setting its innerHTML to that of the <p> element. That works fine except that the text appear as HTML rather than as formatted text.

So for example a user might have entered something like:

"An old silent pond...
A frog jumps into the pond,
splash! Silence again."

Then when the time comes to edit the text, it would appear as:

"An old silent pond...<br>A frog jumps into the pond,<br>splash! Silence again."

Is there a way to make sure that what is displayed for editing is interpreted HTML / formatted text rather than raw HTML? I do need the formatting to be interpreted - I don't want to just strip out the HTML tags.

PS: I assume that textarea is the right way to create a window to edit some text, but I'm not married to it.

Upvotes: 1

Views: 3469

Answers (3)

Stephen P
Stephen P

Reputation: 14800

It sounds like you want to be able to edit the text while seeing and retaining the formatting? This is not something that can be done in a plain <textarea> -- you may want to look at wysiwyg editors such as TinyMCE or CKEditor

Another possibility is the HTML5 contenteditable attribute, and a javascript polyfill to support pre-HTML5 browsers.


See Storing the Changes for a basic suggestion for saving the changes made in a contenteditable section, or search the web for save contenteditable changes for many articles on the subject.


Also, Using the HTML5 attribute "contenteditable" to create a WYSIWYG walks through building up a simplistic editor (Now with Plain Ugly Buttons!)

Upvotes: 3

RobG
RobG

Reputation: 147363

The content of a textarea element isn't parsed as HTML. There are a number of HTML based editors available, Google is your friend.

A textarea element's content is its value. The HTML specification does not define innerHTML, textContent or innerText properties for textarea elements so you should use the value property to access the value.

Upvotes: 0

Explosion Pills
Explosion Pills

Reputation: 191729

If available, set textContent instead of innerHTML.

textarea.textContent = p.innerHTML;

If you need to support IE8, use innerText if textContent is not there.

http://jsfiddle.net/yUMtj/

EDIT: As @RobG indicates, use .value instead of .textContent for even better compatibility.

Upvotes: 1

Related Questions