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
Here’s a jsFiddle demo of my answer. The demo uses CoffeeScript, but you can convert it to plain JavaScript if you need to.
The important part, in JavaScript:
var endIndex = textField.value.length;
if (textField.setSelectionRange) {
textField.setSelectionRange(endIndex, endIndex);
}
I’m posting this answer because I already wrote it for someone else who had the same question. This answer doesn’t cover as many edge cases as the top answers here, but it works for me, and has a jsFiddle demo you can play with.
Here is the code from the jsFiddle, so this answer is preserved even if the jsFiddle disappears:
moveCursorToEnd = (textField) ->
endIndex = textField.value.length
if textField.setSelectionRange
textField.setSelectionRange(endIndex, endIndex)
jQuery ->
$('.that-field').on 'click', ->
moveCursorToEnd(this)
:
Try clicking in the text field. The cursor will always jump to the end.
body {
margin: 1em;
}
.field {
margin-bottom: 1em;
}