Reputation: 727
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 & char</div>
and user sees this & char
in textbox.
Desire HTML output
<div>this & char</div>
and user sees this & char
in textbox.
Upvotes: 4
Views: 1942
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
Reputation: 33
You're using .html()
which is the reason the &
gets translated to &
. Since it's an input, it must be in plain text and hence, when you write &
in an input field, it's displayed as a text.
$('#textbox').val($('#div').text());
Upvotes: 2