1

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.

Nick Brown
  • 1,167
  • 1
  • 21
  • 38
  • 1
    Why are you not just typing '<' and '>' than? I don't think the textarea will render anything inside it. It is just plain text. Also, what do you mean with the difference between manually typed or by hand? Isn't that the same? – putvande Aug 13 '13 at 21:53
  • Using val works just fine, i just tried it in your example – Ibu Aug 13 '13 at 21:54
  • 1
    possible duplicate of [HTML Entity Decode](http://stackoverflow.com/questions/5796718/html-entity-decode) (treating as an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)). – cmbuckley Aug 13 '13 at 22:01
  • @putvande Because the data being inserted is coming in from a database, so I can't just type `>` and `<`. Also, I do mean manually == typed by hand, I think you may have missed the word "not" when reading. – Nick Brown Aug 13 '13 at 22:28

2 Answers2

3

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.

Community
  • 1
  • 1
cmbuckley
  • 40,217
  • 9
  • 77
  • 91
  • This worked, thank you. I think you're right, what I was really after was the HTML encoding/decoding rather than the fail-to-replace issue. Thanks for the link. – Nick Brown Aug 13 '13 at 22:28
1

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 >)

Sergio
  • 28,539
  • 11
  • 85
  • 132