When I try to do .focus()
I expect to set focus on input element and to see cursor after last character of the value. And I see it in IE.
In safari/chrome input gets focus and all text is selected. In firefox/opera input gets focus, but cursor is in the beginning.
What could I do to prevent that and get correct behavior for all browsers?
An example is here: http://jsbin.com/ozojol/edit#javascript,html
PS. focus().val('').val(value)
method doesn't work in IE... What other workarounds exist?
You can use the input's selectionStart
and selectionEnd
properties in most browsers and some nasty TextRange
stuff in IE < 9. Here's some code adapted from an answer to a similar question.
Demo: http://jsbin.com/azapuy
Code:
function moveCaretToEnd(el) {
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();
}
}
var input = $('#i')[0];
input.focus();
moveCaretToEnd(input);
There is a great lightweight plugin to move the caret to the end of the content within your element. jQuery Caret
Live Demo
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