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.

4
  • 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? Commented Aug 13, 2013 at 21:53
  • Using val works just fine, i just tried it in your example Commented Aug 13, 2013 at 21:54
  • 1
    possible duplicate of HTML Entity Decode (treating as an XY problem). Commented Aug 13, 2013 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. Commented Aug 13, 2013 at 22:28

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.