JSFiddle - React, Tailwind, and code Playground

by Ranganadh Paramkusam

HTML

<textarea id="text" rows="20" cols="80"></textarea>
<input type="button" id="btn">

JavaScript

function insertAtCursor(myField, myValue) {
  if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
}

document.getElementById('btn').onclick = function() {
  insertAtCursor(document.getElementById('text'), '%firstName%');
}