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

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

    Try this, it has worked for me:

    //input is the input element
    
    input.focus(); //sets focus to element
    var val = this.input.value; //store the value of the element
    this.input.value = ''; //clear the value of the element
    this.input.value = val; //set that value back.  
    

    For the cursor to be move to the end, the input has to have focus first, then when the value is changed it will goto the end. If you set .value to the same, it won't change in chrome.

提交回复
热议问题