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

后端 未结 30 3996
时光说笑
时光说笑 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:24

    This problem is interesting. The most confusing thing about it is that no solution I found solved the problem completely.

    +++++++ SOLUTION +++++++

    1. You need a JS function, like this:

      function moveCursorToEnd(obj) {
      
        if (!(obj.updating)) {
          obj.updating = true;
          var oldValue = obj.value;
          obj.value = '';
          setTimeout(function(){ obj.value = oldValue; obj.updating = false; }, 100);
        }
      
      }
      
    2. You need to call this guy in the onfocus and onclick events.

      
      

    IT WORKS ON ALL DEVICES AN BROWSERS!!!!

提交回复
热议问题