Insert text to focused position of input field

Insert text to focused position of input field using jquery

by John Kiran

HTML

<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />

JavaScript

$("#btn").on('click', function() {
   var caretPos =document.getElementById("txt").selectionStart;
   var caretEnd = document.getElementById("txt").selectionEnd;
   var textAreaTxt = $("#txt").val();
   var txtToAdd = "stuff";
   $("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring( caretEnd ) );
   
   $('#txt').focus();
   document.getElementById('txt').selectionStart = caretPos + txtToAdd.length
   document.getElementById('txt').selectionEnd = caretPos + txtToAdd.length
   
});