0

I want to change the value of the char at the index of the caret to "[br]".
example of what i mean: lets say we have a textbox and a user enters some text, after a while he remembered that he forgot to start a new line, so he moves his caret to the location where he wants a new line and press return\enter. i want to add to that point the string "[br]", using javascript only. here is what i got now:

<textarea id="textarea" onkeydown="javascript:DoLine();"></textarea>

And here is the DoLine() function:

    function DoLine() {
    if (event.keyCode == 13) {
      var text = document.getElementById('textarea').value;
      text += "[br]";
      if (text.indexOf("[br]") != text.length) {
        var getTextAfter = text[text.lastIndexOf("[br]")] += "\r";
      }
      document.getElementById('textarea').value = text;
    }
  }

this code adds the "[br]" at the end of the textarea instade of where the caret is. I dont really know how to get the index of the caret so i could just convert the text var into an array of chars then add "[br]" at the index of the caret. So anyone got any idea of how can I make my code work the way i wanted it to? or any idea how to get the caret location?
PS: by caret i mean this:
enter image description here
Thank you :)

Shaked Dahan
  • 392
  • 4
  • 19

1 Answers1

1

Thanks to @Tyr i found the answer, this function fixed it:

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, el.selectionStart) + 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();
    }
}
Shaked Dahan
  • 392
  • 4
  • 19