1

I'm receiving JSON data from an ASP.NET web service that has been HtmlEncoded with Microsoft's AntiXSS library (Encoder.HtmlEncode()) and then returned as JSON via a jQuery Ajax call.

I am populating edit form inputs with this data like so: $('descriptionTextBox').val(object.Description);

Other times, I may just be appending it as Html to the page which displays the data as expected: $('descriptionSpan').html(object.Description);

Obviously, this resulted in the form inputs displaying encoded data if the string originally contained Html or characters that were encoded. To decode the data for display in inputs, I am using the following:

function decodeHtml(encodedStr) {
    return $("<div/>").html(encodedStr).text();
}

like so $('descriptionTextBox').val(decodeHtml(object.Description));

Is this the proper way encoded data should be set on forms/inputs with JavaScript?

Jason Eades
  • 1,547
  • 5
  • 16
  • 31

1 Answers1

1

Yes, I think that's fine. For an alternative way to decode strings containing html entities please take a look at this answer: https://stackoverflow.com/a/9609450/240324.

I personally like this method more, because it doesn't creates an html element just to decode a string, however it's nothing wrong with your method.

Community
  • 1
  • 1
Tamás Pap
  • 17,777
  • 15
  • 70
  • 102
  • 1
    I had seen that question, noticed the accepted answer was doing what I was doing, and didn't think to look at the other answers. Thanks. – Jason Eades Apr 02 '13 at 20:24