0

My question is simple, but I can't figured it out.

I'm inserting text in the textarea, using a method that I found around here. That method, insert the text in the actual cursor position, that's fine.

But I want to position the cursor between the inserted text. The text I'll be inserting is:****, __, ~~~~ and [](http://) I know, it's just some random symbols. But it is for a eregi. I want to position the cursor between the chracters inserted, on **here**, _here_ and ~~HERE~~, the last one I need to position between the first [], it is [HERE](http://).

It shouldn't be that hard, but I just don't know how to do this. Any help?

Community
  • 1
  • 1
NuM3
  • 17
  • 5

1 Answers1

0

Use the following functions:

Working Example Caret Test

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  } else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

function setCaretToPos(input, pos) {
  setSelectionRange(input, pos, pos);
}

$("#addStarsCode").click(function() {
  var my_i_val = $("#my_textarea").val();

  $("#my_textarea").val(my_i_val + '****');
  setCaretToPos($("#my_textarea")[0], $("#my_textarea").val().length-2);
});
<textarea id=my_textarea name=my_textarea> I Am A Default Text</textarea><br>
<button id=addStarsCode>Add ****</button>