set cursor to specific position on specific line in a textarea

前端 未结 1 1825
陌清茗
陌清茗 2020-12-02 01:44

I am trying to somewhat duplicate the \"autocorrect\" functionality seen in programs like Microsoft Office\'s Outlook.

For starters, anytime a user types \"a \" (the

相关标签:
1条回答
  • 2020-12-02 02:16

    I've updated your fiddle see: http://jsfiddle.net/eghpf/2/

    I've added var currentPosition which is used in this method

    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();
      }
    }
    

    Which comes from this jQuery Set Cursor Position in Text Area

    What happens (is the reason why the cursor is always on the last position); is when you call $('#systemNotesbuilder').val(arrayOfLines.join("\n")); the entire value gets overwritten with a new value placing the cursor after that new value. The call to set the cursor is (and should) be after that call.

    0 讨论(0)
提交回复
热议问题