I have a textbox that when I put on focus I want the cursor to goto the end of the textbox.
The solution that keeps coming up is just
this.value = t
Simple And Working 100%
1.Focus
2.Take the value
3.Empty It
4.Put the value back
$("#catg_name").focus();
var value = $("#catg_name").val();
$("#catg_name").val('');
$("#catg_name").val(value);
This JSFiddle shows you how it works. jQuery has been used for simplicity in this example, but it can be completely omitted if one desires so. setSelectionRange
function is a DOM function anyway.
In general it does this:
input.focus();
input.setSelectionRange(inputValueLength, inputValueLength);
Obtaining input and its value length can be obtained using DOM functionality or using library functions (as in jQuery).
I haven't tested in other browsers but running in Chrome it allows to set a larger than actual position and caret will be positioned at the end. So something like:
input.setSelectionRange(1000,1000);
will work as expected (provided your text is shorter than 1000 characters. :)
Note: This function isn't supported in IE8 and older. All latest versions of most used browsers support it. For older versions of IE resort to text ranges.
You need to move the caret using either the selectionStart
and selectionEnd
properties or setSelectionRange()
method of the input. IE < 9 does not support these though, so you need to use the input's createTextRange() method in those browsers.
Code:
function moveCaretToEnd(el) {
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();
}
}