showing results for - "javascript insert text in textarea at cursor position"
Eva
16 Jan 2019
1function insertAtCaret(areaId, text) {
2  var txtarea = document.getElementById(areaId);
3  var strPos = 0;
4  var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
5            "ff" : (document.selection ? "ie" : false));
6  if (br == "ie") {
7    txtarea.focus();
8    var range = document.selection.createRange();
9    range.moveStart('character', -txtarea.value.length);
10    strPos = range.text.length;
11  } else if (br == "ff") strPos = txtarea.selectionStart;
12
13  var front = (txtarea.value).substring(0, strPos);
14  var back = (txtarea.value).substring(strPos, txtarea.value.length);
15  txtarea.value = front + text + back;
16  strPos = strPos + text.length;
17  if (br == "ie") {
18    txtarea.focus();
19    var range = document.selection.createRange();
20    range.moveStart('character', -txtarea.value.length);
21    range.moveStart('character', strPos);
22    range.moveEnd('character', 0);
23    range.select();
24  } else if (br == "ff") {
25    txtarea.selectionStart = strPos;
26    txtarea.selectionEnd = strPos;
27    txtarea.focus();
28  }
29}