Append text in TextArea at cursor location using Javascript Monday, Sep 19 2011 

I have a TextArea, textBox and a button. TextArea has some text e.g This is a cat.

Now my requirement is If someone set cursor position in TextArea and enter text in textbox and click on button the text should be append in cursor position instead of last. e.g.

TextArea: This is a cat.

Cursor position: after “a” Entered Text in TextBox: black

Output: This is a black cat.

 

function insertTextAtCursor(el, text) {
var val = el.value, endIndex, range;
if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
endIndex = el.selectionEnd;
el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
el.focus();
range = document.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}

 

That's it.

 

Scaffolding – ASP.NET, NuGet, Entity Framework Code First and More Tuesday, Sep 6 2011 

Watch video by Steve here:

http://channel9.msdn.com/Events/MIX/MIX11/FRM13/player?w=960&h=544