Question:
When a specific text field gains focus, position the cursor at the end of the text field. The solution should work with IE7, Opera, Chrome and Firefox.
To make things a little easier, this behavior is only necessary when the current value of the text field is a fixed value. (Say "INIT")
Incomplete solutions:
One would expect this to be quite simple, but I could not find an answer on SO that works in all browsers. The following answers do NOT work:
$("#test").focus(function() { // This works for Opera only // Also tested with $(this).val($(this).val()); if (this.value == "INIT") { this.value = ""; this.value = "INIT"; } }); $("#test").focus(function() { // This works for IE and for Opera if (this.value == "INIT") { setCaretPosition(this, 4); } });
I got the setCaretPosition function from SO questions and saw it on different blogs as well:
function setCaretPosition(ctrl, pos) { if (ctrl.setSelectionRange) { //ctrl.focus(); // can't focus since we call this from focus() // IE only ctrl.setSelectionRange(pos, pos); } else if (ctrl.createTextRange) { // Chrome, FF and Opera var range = ctrl.createTextRange(); range.collapse(true); range.moveEnd('character', pos); // Also tested with this range.moveStart('character', pos); // and this line in comment range.select(); } }
Fiddle
I installed jsFiddle .
source share