Last active
September 27, 2017 13:12
-
-
Save webolizzer/be16dfb10021abf87088404ea76a9d3f to your computer and use it in GitHub Desktop.
How to insert text into a textarea where the cursor is
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// jQuery version | |
// @author https://stackoverflow.com/a/15977052/2337281 | |
// Example Usage: | |
// <textarea id="txt" rows="15" cols="70">There is some text here.</textarea> | |
// <input type="button" id="btn" value="OK" /> | |
// | |
jQuery("#btn").on('click', function() { | |
var $txt = jQuery("#txt"); | |
var caretPos = $txt[0].selectionStart; | |
var textAreaTxt = $txt.val(); | |
var txtToAdd = "stuff"; | |
$txt.val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) ); | |
}); | |
// | |
// Plain JavaScript version | |
// @author https://stackoverflow.com/a/1064139/2337281 | |
// Example Usage: | |
// <textarea id="textareaid"></textarea> | |
// <a href="#" onclick="insertAtCaret('textareaid', 'text to insert');return false;">Click Here to Insert</a> | |
// | |
function insertAtCaret(areaId,text) { | |
var txtarea = document.getElementById(areaId); | |
var scrollPos = txtarea.scrollTop; | |
var strPos = 0; | |
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? | |
"ff" : (document.selection ? "ie" : false ) ); | |
if (br == "ie") { | |
txtarea.focus(); | |
var range = document.selection.createRange(); | |
range.moveStart ('character', -txtarea.value.length); | |
strPos = range.text.length; | |
} | |
else if (br == "ff") strPos = txtarea.selectionStart; | |
var front = (txtarea.value).substring(0,strPos); | |
var back = (txtarea.value).substring(strPos,txtarea.value.length); | |
txtarea.value=front+text+back; | |
strPos = strPos + text.length; | |
if (br == "ie") { | |
txtarea.focus(); | |
var range = document.selection.createRange(); | |
range.moveStart ('character', -txtarea.value.length); | |
range.moveStart ('character', strPos); | |
range.moveEnd ('character', 0); | |
range.select(); | |
} | |
else if (br == "ff") { | |
txtarea.selectionStart = strPos; | |
txtarea.selectionEnd = strPos; | |
txtarea.focus(); | |
} | |
txtarea.scrollTop = scrollPos; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment