I've been trying to set content of a text input dynamically using JS, the problem I encountered is I can not have the browser render the special symbols rather than chars so for example
document.getElementById("textField").value = "nbsp";
Instead of displaying a space it displays  , anybody got any idea?
Thanks a lot
I've been trying to set content of a text input dynamically using JS, the problem I encountered is I can not have the browser render the special symbols rather than chars so for example
document.getElementById("textField").value = "nbsp";
Instead of displaying a space it displays  , anybody got any idea?
Thanks a lot
Share Improve this question asked Sep 13, 2013 at 6:49 user1935724user1935724 5541 gold badge6 silver badges19 bronze badges 3- Try this stackoverflow./a/784611/2261259 – Voonic Commented Sep 13, 2013 at 6:55
- @shadow: That's not what he wants. He wants the special character to be entered in the text field, in this case it's a non-breaking space. He doesn't want its HTML entity. – Joe Simmons Commented Sep 13, 2013 at 6:59
-
The code in the question does not have the effect described. Did you actually mean
" "
instead of just"nbsp"
? – Jukka K. Korpela Commented Sep 13, 2013 at 10:08
5 Answers
Reset to default 4It seems that you want to enter special characters like NO-BREAK SPACE in a JavaScript string literal. You can do that directly, provided that the character encoding of the file containing JavaScript code is properly declared, as it should be anyway:
document.getElementById("textField").value = ' ';
Here the character between apostrophes is the real NO-BREAK SPACE character. In rendering, it is usually indistinguishable from normal SPACE, but it has different effects. Similarly you can write e.g.
document.getElementById("textField").value = 'Ω';
using the Greek letter capital omega directly.
If you do not know how to enter such characters (e.g., via Windows CharMap program) or if you cannot control character encoding issues, you can use JavaScript Unicode escape notations for characters, e.g.
document.getElementById("textField").value = '\u00A0'; // no-break space
or
document.getElementById("textField").value = '\u03A9'; // capital omega
For the small set of characters with Unicode numbers less than 0x100, you can alternatively use \x
escapes, e.g. '\xA0'
instead of '\u00A0'
. (But if you didn’t know this, it is better to learn to use the universal \u
escape insteadd.)
is an HTML entity and you can't put an HTML entity in a text field like that.
Try using unicode, like this:
document.getElementById("textField").value = '\xA0';
What about using jquery and this:
$("#textField").html(' ').text()
Or in more general:
$(element).html(encodedString).text()
document.getElementById("textField").value = " ";
you should use " " instead of "nbsp"