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

什么是最好的方法(我认为最简单的方法)将光标放置在输入文本元素的文本末尾,通过JavaScript - 焦点已设置为元素之后?


I faced this same issue (after setting focus through RJS/prototype) in IE. Firefox was already leaving the cursor at the end when there is already a value for the field. IE was forcing the cursor to the beginning of the text.

The solution I arrived at is as follows:

<input id="search" type="text" value="mycurrtext" size="30" 
       onfocus="this.value = this.value;" name="search"/>

This works in both IE7 and FF3


There's a simple way to get it working in most browsers.

this.selectionStart = this.selectionEnd = this.value.length;

However, due to the *quirks of a few browsers, a more inclusive answer looks more like this

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);

Using jQuery (to set the listener, but it's not necessary otherwise)

$('#el').focus(function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='el' type='text' value='put cursor at end'>

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.

链接地址: http://www.djcxy.com/p/68448.html

上一篇: 导航表单域并用箭头键编辑文本

下一篇: 使用JavaScript将光标置于文本输入元素中的文本末尾