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
this & char
in textbox.
Desire HTML output
<div>this & char</div>
and user sees this & char
in textbox.
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());
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' />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.