6

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.

MeetM
  • 1,410
  • 17
  • 25

3 Answers3

3

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!

Community
  • 1
  • 1
veeTrain
  • 2,915
  • 2
  • 26
  • 43
  • but this moves the cursor position. Its `contenteditable` div – MeetM Apr 25 '12 at 15:19
  • @MeetM; yes, wiping out the `html()` of the div will move the cursor position. You never mentioned what event was generating the need to insert text. Presumably you must be trying to bind to a keyboard event. But if you are inserting text into something while someone is typing, they might not like it. – veeTrain Apr 25 '12 at 15:38
3

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 "));
Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • A contentEditable div with line breaks will always have more nodes in the form of
    ? How is it possible to have a single text node?
    – Rafael Jun 03 '14 at 02:45
  • 1
    @RafaelDiaz: The code in the question has a contenteditable element with a single text node. In general, obviously it's unlikely that an application using contenteditable would be much use if it only allowed the user to edit a single text node with no formatting. – Tim Down Jun 03 '14 at 09:05
0

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);
M Rostami
  • 4,035
  • 1
  • 35
  • 39