432

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 36

1
2
-1

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);}
Sign up to request clarification or add additional context in comments.

Comments

-1

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

-1

Try the following code:

$('input').focus(function () {
    $(this).val($(this).val());
}).focus()

6 Comments

Is adding trailing whitespace a side effect the OP has indicated they desire?
But why my answer get -2? I dont get it! This is examples it works
Now that you fixed the unspecified side effect, it's less obviously wrong (in the undesired-behavior sense), but I can understand why it would have gotten downvoted prior to that point. At this point, the reason I'm not upvoting is potentially poor performance -- reading and writing a value of unbounded length has potential to be slow; the setSelectionRange approach is certainly much more efficient when/where supported.
(Well -- that, and I'm not sure what it adds to existing answers that also worked by re-setting the preexisting value; if it does add something new/important, adding some text describing what that is, rather than only code, would help).
Sure -- and did the OP indicate in the question that they wanted a space? If not, it's not part of the specification; thus, "unspecified".
|
-1

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();
    }
}

Comments

-2
input = $('input'); 
input.focus().val(input.val()+'.'); 
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}

Comments

-2

Well, I just use:

$("#myElement").val($("#myElement").val());

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.