MeetM
MeetM

Reputation: 1430

How to add / insert / update text inside contenteditable div at a particular position?

The HTML code looks like this

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

I have to insert some new text based on some event at a particular position in the above div. The event calls the function say updateDiv(txt, positon). For example it says
updateDiv("more ",5);

So the div should become be

<div id="txtarea" contenteditable="true">Some more text</div>

I tried a lot of javascript and jquery but nothing seem to work.

Upvotes: 6

Views: 7770

Answers (3)

veeTrain
veeTrain

Reputation: 2915

Here's how I did it:

var position = 5,
    txt = "more ";
var current = $("#txtarea").html();
//alert(current.substring(0, position))
var endVal = current.substring(position);
var newValue = current.substring(0, position) + txt + endVal;
$("#txtarea").html(newValue);​

jsfiddle displaying it 'in action'.

Edit: Updated the jsfiddle with the approach listed in a comment above to this post. Pretty slick!

Upvotes: 3

M Rostami
M Rostami

Reputation: 4195

use this function :

String.prototype.splice = function( position, newstring ) {
    return (this.slice(0,position) + newstring + this.slice(position));
};

and use this function as :

var oldstr=$('#txtarea').html();
var newstr='more';
var position = 5;
$('#txtarea').html(oldstr.splice(position , newstr);

Upvotes: 0

Tim Down
Tim Down

Reputation: 324707

If the content of your editable <div> always consists of a single text node, this is relatively simple and you can use the code below.

var div = document.getElementById("txtarea");
var textNode = div.firstChild;
textNode.data = textNode.data.slice(0, 5) + "more " + textNode.data.slice(5);

Otherwise, you'll need to read about DOM Ranges (note that they are not supported in IE < 9) and use something like this answer to create a range corresponding to character indices within the content and then use insertNode().

var div = document.getElementById("txtarea");
var range = createRangeFromCharacterIndices(div, 5, 5);
range.insertNode(document.createTextNode("more "));

Upvotes: 3

Related Questions