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?
36 Answers
I tried the suggestions before but none worked for me (tested them in Chrome), so I wrote my own code - and it works fine in Firefox, IE, Safari, Chrome...
In Textarea:
onfocus() = sendCursorToEnd(this);
In Javascript:
function sendCursorToEnd(obj) {
var value = obj.value; //store the value of the element
var message = "";
if (value != "") {
message = value + "\n";
};
$(obj).focus().val(message);}
Comments
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)
<div class="field">
<label for="pressure">Blood pressure</label>:
<input class="that-field" type="text" name="pressure" id="pressure" value="24">
</div>
<p>
Try clicking in the text field. The cursor will always jump to the end.
</p>
body {
margin: 1em;
}
.field {
margin-bottom: 1em;
}
Comments
Try the following code:
$('input').focus(function () {
$(this).val($(this).val());
}).focus()
6 Comments
setSelectionRange approach is certainly much more efficient when/where supported.Though I'm answering too late, but for future query, it will be helpful. And it also work in contenteditable div.
From where you need to set focus at end; write this code-
var el = document.getElementById("your_element_id");
placeCaretAtEnd(el);
And the function is -
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}