Manu
Manu

Reputation: 4500

jquery .html() removes trailing spaces

I want to set "someting " as the html inside a div, but .html() seem to remove the trailing spaces.

It's inside a contenteditable div, so when the users starts typing there's a space missing between "something" and what he types.

HTML

<div id="text" contenteditable="true"></div>

JAVASCRIPT

$('div#text').html('something          ');

This shows "something_" inside the div, but when you start typing it appears right next to the rest of the text.

Upvotes: 2

Views: 1949

Answers (3)

The Alpha
The Alpha

Reputation: 146191

If you like it using css

HTML

<div contenteditable="true" id="test"></div>

CSS

div#test:before{
    content: '>\0000a0\0000a0';
    /*or  content: 'Something\0000a0\0000a0';*/
}

DEMO.

Upvotes: 0

VisioN
VisioN

Reputation: 145408

In order to set visible spaces in HTML, they should be in the form of &nbsp;, e.g.

​$("#text").html("something&nbsp;&nbsp;")​​​​;

An option is to make basic spaces transformation using your own function:

function spaceToNbsp(str) {
    return str.replace(/ /g, "&nbsp;");
}

$("#text").html(spaceToNbsp("something  "))​​​​;

DEMO: http://jsfiddle.net/NAWY3/

Upvotes: 5

Tallmaris
Tallmaris

Reputation: 7590

Try using &nbsp; instead of spaces:

$('#div_id').html("something&nbsp;");

Upvotes: 1

Related Questions