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
  • 402
  • 5
  • 22
  • 1
    Take a look here: http://stackoverflow.com/questions/3308292/inserting-text-at-cursor-in-a-textarea-with-javascript/3308539#3308539 – Tyr May 04 '15 at 19:11
  • Need to use encodeURIComponent to get the value of the textbox with the formatting so that you can add new lines. – frenchie May 04 '15 at 19:12

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
  • 402
  • 5
  • 22