Search code examples
jquerytextboxdecodeencode

Decode text prior to $("#textbox").val() call?


My web page makes AJAX calls to a server and displays the result in the browser. The contents of the result will frequently contain a portion of the text string that the user submitted in the AJAX request. So if the user types <script> in his query, the returned output will likely contain the phrase <script> too. The server encodes the response before sending it, however, so the returned phrase actually would be received as &lt;script&gt;

This is all well and good. The scripting vulnerability is removed and the browser properly displays <script> when showing the response.

The problem is when I want to take the return value and stuff it into a text box. Consider:

$(“#someTextBox”).val(“&lt;script&gt;”);

The contents of the text box are displayed in encoded form (i.e. &lt;script&gt;) instead of in decoded form (i.e. <script>).

Questions:

[1] How do I decode the value prior to the call to val()?

[2] Am I introducing a security vulnerability by doing so?


Solution

  • Quite possibly a more straightforward method for doing this, but seems to get the desired result.

    http://jsfiddle.net/ZPLTc/

    More info here ( where I got concept ) http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb