Clinton Lam
Clinton Lam

Reputation: 727

Prevent javascript from auto escaping & character

I am seeing & in my textbox but I only want &. I think it is something to do with the way browser interpret javascript .innerHTML. The text with & must pass through div. For some reason, I can't directly assign value to the text box.

HTML Code

<div id='div'></div>
<input id='textbox' type='text' />

Javascript Code

var str = 'this & char';
$('#div').append("<div>" + str + "</div>");
$('#textbox').val($('#div').html());

Actual HTML output

<div>this &amp; char</div>

and user sees this &amp; char in textbox.

Desire HTML output

<div>this & char</div>

and user sees this & char in textbox.

Upvotes: 4

Views: 1942

Answers (2)

Hassan Imam
Hassan Imam

Reputation: 22534

Instead of using html() use text(). html() treats the string as HTML, text() treats the content as text.

var str = 'this & char';
$('#div').append("<div>" + str + "</div>");
$('#textbox').val($('#div').text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'></div>
<input id='textbox' type='text' />

Upvotes: 1

Luicy
Luicy

Reputation: 33

You're using .html() which is the reason the & gets translated to &amp;. Since it's an input, it must be in plain text and hence, when you write &amp; in an input field, it's displayed as a text.

$('#textbox').val($('#div').text());

Upvotes: 2

Related Questions