Nick Brown
Nick Brown

Reputation: 1167

jQuery empty textarea that contains data

Curious problem. I need to empty a <textarea> then replace it with other content. The tests in the JSFiddle will work if nothing is manually typed, but as soon as anything is entered in the textarea by hand, the methods will cease to work.

http://jsfiddle.net/ecFjH/

I understand that I can simply just .val('New stuff here'), however I need HTML entities such as &gt; and &lt; to appear as < and >, which .val() will not accomplish.

Upvotes: 1

Views: 118

Answers (2)

cmbuckley
cmbuckley

Reputation: 42468

It sounds like your real problem is that you want to decode HTML entities to render them in a text area. You could use the following to do this:

var content = 'text &gt; HTML';
$('#myText').val($('<div/>').html(content).text());

However, you should only do this with trusted content. If the content for the textarea is not created by you, it could contain malicious HTML, which you would unsafely be creating on the page.

For a more thorough example, see this answer to essentially the same question; note that the accepted answer repeats the above, but the linked answer is safer.

Upvotes: 3

Sergio
Sergio

Reputation: 28837

Your text area has no html. use just $('#myText').val('Button 2 was pressed'); that will remove the previous content and put the text "Button 2 was pressed".

Check here (updated with < and >)

Upvotes: 1

Related Questions