DavidB
DavidB

Reputation: 2596

Performing jQuery val() against a textbox with html entities

I have set up my issue using a simple js fiddle http://jsfiddle.net/um788f6q/

<input type="text" id="yo">
$("#yo").val('hell&#39;o')

Basically I would like to know if there is a way to display an apostrophe rather than the encoded string. I have encoded the values like this on the server to prevent xss attacks, so decoding is not realy a valid option.

Thanks

Upvotes: 3

Views: 5321

Answers (5)

LAB3W.ORJ
LAB3W.ORJ

Reputation: 1

Instead of retrieving the value of a field or an element with .val() / .text() or .html() and you want to encode it.

You can use serialize() and send it in a data ajaxer easily...

and retrieve field name with value (with any few characters) or the whole html form ;)

Example :

var text = $("input#my_input").val('Good Music &#x1F3B6;');
console.log(text);
            
var text = $("input#my_input").serialize();
console.log(text);

Who returns: Good Music 🎶

Upvotes: 0

shahmanthan9
shahmanthan9

Reputation: 523

This should help you

var tp = 'hell&#39;o';
var new_tp = $('<textarea />').html(tp).text();
$('#yo').val(new_tp); 

JS Fiddle

Upvotes: -2

SimarjeetSingh Panghlia
SimarjeetSingh Panghlia

Reputation: 2200

Try this

var test = 'hell&#39;o';
var decoded = $('<div/>').html(test).text();
$("#yo").val(decoded);

Fiddle Demo

Upvotes: 0

Quentin
Quentin

Reputation: 943759

Basically I would like to know if there is a way to display an apostrophe rather than the encoded string.

Nothing sane.

The value property deals in text, not HTML.

As a horrible hack you could convert it to text by parsing the HTML and then reading the resulting text node.

$("#yo").val($("<div />").html('hell&#39;o').text());

… but don't. Solve the real problem instead.

I have encoded the values like this on the server to prevent xss attacks

Don't do that.

You're inserting the data into JavaScript, not into HTML.

Don't use a defence for HTML when you aren't dealing in HTML. It could leave you vulnerable.

The appropriate way to encode data for inserting into JavaScript is to use a JSON encoder. (Then encode the resulting JSON with entities if you are putting the JSON in an HTML attribute value, or escape any / characters if you are putting it in a <script> element).

Upvotes: 11

banana_Ai
banana_Ai

Reputation: 54

You can replace $#39; by ' in JS and replace it back on the server side.

<input type="text" id="yo">
$("#yo").val('hell&#39;o'.replace('&#39;',"'"))

Upvotes: -2

Related Questions