Use JavaScript to place cursor at end of text in text input element

后端 未结 30 3370
时光说笑
时光说笑 2020-11-22 02:48

What is the best way (and I presume simplest way) to place the cursor at the end of the text in a input text element via JavaScript - after focus has been set to the element

30条回答
  •  名媛妹妹
    2020-11-22 03:26

    It's 2019 and none of the methods above worked for me, but this one did, taken from https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/

    function moveCursorToEnd(id) {
      var el = document.getElementById(id) 
      el.focus()
      if (typeof el.selectionStart == "number") {
          el.selectionStart = el.selectionEnd = el.value.length;
      } else if (typeof el.createTextRange != "undefined") {           
          var range = el.createTextRange();
          range.collapse(false);
          range.select();
      }
    }
    
    Move cursor to end

提交回复
热议问题