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?
Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.
If you ever had a specific case where you had to retrieve the position of a caret (your cursor's position) inside an HTML input field, you can do so using the selectionStart property of an input's value.
Javascript - Caret Position The mouse moves the cursor. Text fields use a caret to indicate where text is inserted. Left clicking the mouse typically sets the caret location.
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'>
Using Vanilla JS (borrowing addEvent
function from this answer)
// Basic cross browser addEvent function addEvent(elem, event, fn){ if(elem.addEventListener){ elem.addEventListener(event, fn, false); }else{ elem.attachEvent("on" + event, function(){ return(fn.call(elem, window.event)); }); }} var element = document.getElementById('el'); addEvent(element,'focus',function(){ var that = this; setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0); });
<input id='el' type='text' value='put cursor at end'>
Chrome has an odd quirk where the focus event fires before the cursor is moved into the field; which screws my simple solution up. Two options to fix this:
focus
to mouseup
. This would be pretty annoying for the user unless you still kept track of focus. I'm not really in love with either of these options.Also, @vladkras pointed out that some older versions of Opera incorrectly calculate the length when it has spaces. For this you can use a huge number that should be larger than your string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With