[javascript] Use JavaScript to place cursor at end of text in text input element

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?

This question is related to javascript

The answer is


I faced this same issue (after setting focus through RJS/prototype) in IE. Firefox was already leaving the cursor at the end when there is already a value for the field. IE was forcing the cursor to the beginning of the text.

The solution I arrived at is as follows:

<input id="search" type="text" value="mycurrtext" size="30" 
       onfocus="this.value = this.value;" name="search"/>

This works in both IE7 and FF3


It's 2019 and none of the methods above worked for me, but this one did, taken from https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/

_x000D_
_x000D_
function moveCursorToEnd(id) {_x000D_
  var el = document.getElementById(id) _x000D_
  el.focus()_x000D_
  if (typeof el.selectionStart == "number") {_x000D_
      el.selectionStart = el.selectionEnd = el.value.length;_x000D_
  } else if (typeof el.createTextRange != "undefined") {           _x000D_
      var range = el.createTextRange();_x000D_
      range.collapse(false);_x000D_
      range.select();_x000D_
  }_x000D_
}
_x000D_
<input id="myinput" type="text" />_x000D_
<a href="#" onclick="moveCursorToEnd('myinput')">Move cursor to end</a>
_x000D_
_x000D_
_x000D_


I've tried the following with quite great success in chrome

$("input.focus").focus(function () {
    var val = this.value,
        $this = $(this);
    $this.val("");

    setTimeout(function () {
        $this.val(val);
    }, 1);
});

Quick rundown:

It takes every input field with the class focus on it, then stores the old value of the input field in a variable, afterwards it applies the empty string to the input field.

Then it waits 1 milisecond and puts in the old value again.


Notice focus() is at the end, this is for textarea long text compatability.

const end = input.value.length
input.setSelectionRange(end, end)
input.focus()

This problem is interesting. The most confusing thing about it is that no solution I found solved the problem completely.

+++++++ SOLUTION +++++++

  1. You need a JS function, like this:

    function moveCursorToEnd(obj) {
    
      if (!(obj.updating)) {
        obj.updating = true;
        var oldValue = obj.value;
        obj.value = '';
        setTimeout(function(){ obj.value = oldValue; obj.updating = false; }, 100);
      }
    
    }
    
  2. You need to call this guy in the onfocus and onclick events.

    <input type="text" value="Test Field" onfocus="moveCursorToEnd(this)" onclick="moveCursorToEnd(this)">
    

IT WORKS ON ALL DEVICES AN BROWSERS!!!!


Well, I just use:

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

I also faced same problem. Finally this gonna work for me:

jQuery.fn.putCursorAtEnd =  = function() {

  return this.each(function() {

    // Cache references
    var $el = $(this),
        el = this;

    // Only focus if input isn't already
    if (!$el.is(":focus")) {
     $el.focus();
    }

    // If this function exists... (IE 9+)
    if (el.setSelectionRange) {

      // Double the length because Opera is inconsistent about whether a carriage return is one character or two.
      var len = $el.val().length * 2;

      // Timeout seems to be required for Blink
      setTimeout(function() {
        el.setSelectionRange(len, len);
      }, 1);

    } else {

      // As a fallback, replace the contents with itself
      // Doesn't work in Chrome, but Chrome supports setSelectionRange
      $el.val($el.val());

    }

    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Chrome)
    this.scrollTop = 999999;

  });

};

This is how we can call this:

var searchInput = $("#searchInputOrTextarea");

searchInput
  .putCursorAtEnd() // should be chainable
  .on("focus", function() { // could be on any event
    searchInput.putCursorAtEnd()
  });

It's works for me in safari, IE, Chrome, Mozilla. On mobile devices I didn't tried this.


In jQuery, that's

$(document).ready(function () {
  $('input').focus(function () {
    $(this).attr('value',$(this).attr('value'));
  }
}

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

var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);

Super easy (you may have to focus on the input element)

inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;

In jQuery, that's

$(document).ready(function () {
  $('input').focus(function () {
    $(this).attr('value',$(this).attr('value'));
  }
}

Try this, it has worked for me:

//input is the input element

input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.  

For the cursor to be move to the end, the input has to have focus first, then when the value is changed it will goto the end. If you set .value to the same, it won't change in chrome.


Taking some of the answers .. making a single-line jquery.

$('#search').focus().val($('#search').val());

I wanted to put cursor at the end of a "div" element where contenteditable = true, and I got a solution with Xeoncross code:

<input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">

<div id="test" contenteditable="true">
    Here is some nice text
</div>

And this function do magic:

 function pasteHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // non-standard and not supported in all browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}

Works fine for most browsers, please check it, this code puts text and put focus at the end of the text in div element (not input element)

https://jsfiddle.net/Xeoncross/4tUDk/

Thanks, Xeoncross


Super easy (you may have to focus on the input element)

inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;

If the input field just needs a static default value I usually do this with jQuery:

$('#input').focus().val('Default value');

This seems to work in all browsers.


Set the cursor when click on text area to the end of text... Variation of this code is...ALSO works! for Firefox, IE, Safari, Chrome..

In server-side code:

txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")

In Javascript:

function sendCursorToEnd(obj) {
    var value =  $(obj).val(); //store the value of the element
    var message = "";
    if (value != "") {
        message = value + "\n";
     };
    $(obj).focus().val(message);
    $(obj).unbind();
 }

If the input field just needs a static default value I usually do this with jQuery:

$('#input').focus().val('Default value');

This seems to work in all browsers.


<script type="text/javascript">  
    function SetEnd(txt) {  
      if (txt.createTextRange) {  
       //IE  
       var FieldRange = txt.createTextRange();  
       FieldRange.moveStart('character', txt.value.length);  
       FieldRange.collapse();  
       FieldRange.select();  
       }  
      else {  
       //Firefox and Opera  
       txt.focus();  
       var length = txt.value.length;  
       txt.setSelectionRange(length, length);  
      }  
    }   
</script>  

This function works for me in IE9, Firefox 6.x, and Opera 11.x


I just found that in iOS, setting textarea.textContent property will place the cursor at the end of the text in the textarea element every time. The behavior was a bug in my app, but seems to be something that you could use intentionally.


Notice focus() is at the end, this is for textarea long text compatability.

const end = input.value.length
input.setSelectionRange(end, end)
input.focus()

I like the accepted answer a lot, but it stopped working in Chrome. In Chrome, for the cursor to go to the end, input value needs to change. The solution is as follow:

<input id="search" type="text" value="mycurrtext" size="30" 
   onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>

el.setSelectionRange(-1, -1);

https://codesandbox.io/s/peaceful-bash-x2mti

This method updates the HTMLInputElement.selectionStart, selectionEnd, and selectionDirection properties in one call.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

In other js methods -1 usually means (to the) last character. This is the case for this one too, but I couldn't find explicit mention of this behavior in the docs.


Try the following code:

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

<script type="text/javascript">  
    function SetEnd(txt) {  
      if (txt.createTextRange) {  
       //IE  
       var FieldRange = txt.createTextRange();  
       FieldRange.moveStart('character', txt.value.length);  
       FieldRange.collapse();  
       FieldRange.select();  
       }  
      else {  
       //Firefox and Opera  
       txt.focus();  
       var length = txt.value.length;  
       txt.setSelectionRange(length, length);  
      }  
    }   
</script>  

This function works for me in IE9, Firefox 6.x, and Opera 11.x


If you set the value first and then set the focus, the cursor will always appear at the end.

$("#search-button").click(function (event) {
    event.preventDefault();
    $('#textbox').val('this');
    $("#textbox").focus();
    return false;
});

Here is the fiddle to test https://jsfiddle.net/5on50caf/1/


Try this one works with Vanilla JavaScript.

<input type="text" id="yourId" onfocus=" let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">

In Js

document.getElementById("yourId").focus()

_x000D_
_x000D_
document.querySelector('input').addEventListener('focus', e => {
  const { value } = e.target;
  e.target.setSelectionRange(value.length, value.length);
});
_x000D_
<input value="my text" />
_x000D_
_x000D_
_x000D_


After hacking around with this a bit, I found the best way was to use the setSelectionRange function if the browser supports it; if not, revert to using the method in Mike Berrow's answer (i.e. replace the value with itself).

I'm also setting scrollTop to a high value in case we're in a vertically-scrollable textarea. (Using an arbitrary high value seems more reliable than $(this).height() in Firefox and Chrome.)

I've made it is as a jQuery plugin. (If you're not using jQuery I trust you can still get the gist easily enough.)

I've tested in IE6, IE7, IE8, Firefox 3.5.5, Google Chrome 3.0, Safari 4.0.4, Opera 10.00.

It's available on jquery.com as the PutCursorAtEnd plugin. For your convenience, the code for release 1.0 is as follows:

// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea

// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
    jQuery.fn.putCursorAtEnd = function()
    {
    return this.each(function()
    {
        $(this).focus()

        // If this function exists...
        if (this.setSelectionRange)
        {
        // ... then use it
        // (Doesn't work in IE)

        // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
        var len = $(this).val().length * 2;
        this.setSelectionRange(len, len);
        }
        else
        {
        // ... otherwise replace the contents with itself
        // (Doesn't work in Google Chrome)
        $(this).val($(this).val());
        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Google Chrome)
        this.scrollTop = 999999;
    });
    };
})(jQuery);

There's a simple way to get it working in most browsers.

this.selectionStart = this.selectionEnd = this.value.length;

However, due to the *quirks of a few browsers, a more inclusive answer looks more like this

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);

Using jQuery (to set the listener, but it's not necessary otherwise)

_x000D_
_x000D_
$('#el').focus(function(){_x000D_
  var that = this;_x000D_
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id='el' type='text' value='put cursor at end'>
_x000D_
_x000D_
_x000D_

Using Vanilla JS (borrowing addEvent function from this answer)

_x000D_
_x000D_
// Basic cross browser addEvent_x000D_
function addEvent(elem, event, fn){_x000D_
if(elem.addEventListener){_x000D_
  elem.addEventListener(event, fn, false);_x000D_
}else{_x000D_
  elem.attachEvent("on" + event,_x000D_
  function(){ return(fn.call(elem, window.event)); });_x000D_
}}_x000D_
var element = document.getElementById('el');_x000D_
_x000D_
addEvent(element,'focus',function(){_x000D_
  var that = this;_x000D_
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);_x000D_
});
_x000D_
<input id='el' type='text' value='put cursor at end'>
_x000D_
_x000D_
_x000D_


Quirks

Chrome has an odd quirk where the focus event fires before the cursor is moved into the field; which screws my simple solution up. Two options to fix this:

  1. You can add a timeout of 0 ms (to defer the operation until the stack is clear)
  2. You can change the event from focus to mouseup. This would be pretty annoying for the user unless you still kept track of focus. I'm not really in love with either of these options.

Also, @vladkras pointed out that some older versions of Opera incorrectly calculate the length when it has spaces. For this you can use a huge number that should be larger than your string.


Check this solution!

_x000D_
_x000D_
//fn setCurPosition_x000D_
$.fn.setCurPosition = function(pos) {_x000D_
    this.focus();_x000D_
    this.each(function(index, elem) {_x000D_
        if (elem.setSelectionRange) {_x000D_
            elem.setSelectionRange(pos, pos);_x000D_
        } else if (elem.createTextRange) {_x000D_
            var range = elem.createTextRange();_x000D_
            range.collapse(true);_x000D_
            range.moveEnd('character', pos);_x000D_
            range.moveStart('character', pos);_x000D_
            range.select();_x000D_
        }_x000D_
    });_x000D_
    return this;_x000D_
};_x000D_
_x000D_
// USAGE - Set Cursor ends_x000D_
$('#str1').setCurPosition($('#str1').val().length);_x000D_
_x000D_
// USAGE - Set Cursor at 7 position_x000D_
// $('#str2').setCurPosition(7);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p>Set cursor at any position</p>_x000D_
<p><input type="text" id="str1" value="my string here" /></p>_x000D_
<p><input type="text" id="str2" value="my string here" /></p>
_x000D_
_x000D_
_x000D_


For all browsers for all cases:

function moveCursorToEnd(el) {
    window.setTimeout(function () {
            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();
        }
    }, 1);
}

Timeout required if you need to move cursor from onFocus event handler


Simple. When editing or changing values, first put the focus then set value.

$("#catg_name").focus();
$("#catg_name").val(catg_name);

While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.

The solution that works cross browser and for all input types is rather simple:

  • get and store the value of input in a variable
  • focus the input
  • set the value of input to the stored value

That way the cursor is at the end of the input element.
So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):

$('.foo').click(function() {
    element_selector = $(this).attr('data-focus-element');
    $focus = $(element_selector);
    value = $focus.val();
    $focus.focus();
    $focus.val(value);
});

Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.


I like the accepted answer a lot, but it stopped working in Chrome. In Chrome, for the cursor to go to the end, input value needs to change. The solution is as follow:

<input id="search" type="text" value="mycurrtext" size="30" 
   onfocus="var value = this.value; this.value = null; this.value = value;" name="search"/>

There's a simple way to get it working in most browsers.

this.selectionStart = this.selectionEnd = this.value.length;

However, due to the *quirks of a few browsers, a more inclusive answer looks more like this

setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);

Using jQuery (to set the listener, but it's not necessary otherwise)

_x000D_
_x000D_
$('#el').focus(function(){_x000D_
  var that = this;_x000D_
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id='el' type='text' value='put cursor at end'>
_x000D_
_x000D_
_x000D_

Using Vanilla JS (borrowing addEvent function from this answer)

_x000D_
_x000D_
// Basic cross browser addEvent_x000D_
function addEvent(elem, event, fn){_x000D_
if(elem.addEventListener){_x000D_
  elem.addEventListener(event, fn, false);_x000D_
}else{_x000D_
  elem.attachEvent("on" + event,_x000D_
  function(){ return(fn.call(elem, window.event)); });_x000D_
}}_x000D_
var element = document.getElementById('el');_x000D_
_x000D_
addEvent(element,'focus',function(){_x000D_
  var that = this;_x000D_
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);_x000D_
});
_x000D_
<input id='el' type='text' value='put cursor at end'>
_x000D_
_x000D_
_x000D_


Quirks

Chrome has an odd quirk where the focus event fires before the cursor is moved into the field; which screws my simple solution up. Two options to fix this:

  1. You can add a timeout of 0 ms (to defer the operation until the stack is clear)
  2. You can change the event from focus to mouseup. This would be pretty annoying for the user unless you still kept track of focus. I'm not really in love with either of these options.

Also, @vladkras pointed out that some older versions of Opera incorrectly calculate the length when it has spaces. For this you can use a huge number that should be larger than your string.


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

Try this one works with Vanilla JavaScript.

<input type="text" id="yourId" onfocus=" let value = this.value; this.value = null; this.value=value" name="nameYouWant" class="yourClass" value="yourValue" placeholder="yourPlaceholder...">

In Js

document.getElementById("yourId").focus()

Well, I just use:

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

Try the following code:

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

While this may be an old question with lots of answers, I ran across a similar issue and none of the answers were quite what I wanted and/or were poorly explained. The issue with selectionStart and selectionEnd properties is that they don't exist for input type number (while the question was asked for text type, I reckon it might help others who might have other input types that they need to focus). So if you don't know whether the input type the function will focus is a type number or not, you cannot use that solution.

The solution that works cross browser and for all input types is rather simple:

  • get and store the value of input in a variable
  • focus the input
  • set the value of input to the stored value

That way the cursor is at the end of the input element.
So all you'd do is something like this (using jquery, provided the element selector that one wishes to focus is accessible via 'data-focus-element' data attribute of the clicked element and the function executes after clicking on '.foo' element):

$('.foo').click(function() {
    element_selector = $(this).attr('data-focus-element');
    $focus = $(element_selector);
    value = $focus.val();
    $focus.focus();
    $focus.val(value);
});

Why does this work? Simply, when the .focus() is called, the focus will be added to the beginning of the input element (which is the core problem here), ignoring the fact, that the input element already has a value in it. However, when the value of an input is changed, the cursor is automatically placed at the end of the value inside input element. So if you override the value with the same value that had been previously entered in the input, the value will look untouched, the cursor will, however, move to the end.


I also faced same problem. Finally this gonna work for me:

jQuery.fn.putCursorAtEnd =  = function() {

  return this.each(function() {

    // Cache references
    var $el = $(this),
        el = this;

    // Only focus if input isn't already
    if (!$el.is(":focus")) {
     $el.focus();
    }

    // If this function exists... (IE 9+)
    if (el.setSelectionRange) {

      // Double the length because Opera is inconsistent about whether a carriage return is one character or two.
      var len = $el.val().length * 2;

      // Timeout seems to be required for Blink
      setTimeout(function() {
        el.setSelectionRange(len, len);
      }, 1);

    } else {

      // As a fallback, replace the contents with itself
      // Doesn't work in Chrome, but Chrome supports setSelectionRange
      $el.val($el.val());

    }

    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Chrome)
    this.scrollTop = 999999;

  });

};

This is how we can call this:

var searchInput = $("#searchInputOrTextarea");

searchInput
  .putCursorAtEnd() // should be chainable
  .on("focus", function() { // could be on any event
    searchInput.putCursorAtEnd()
  });

It's works for me in safari, IE, Chrome, Mozilla. On mobile devices I didn't tried this.


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

If you set the value first and then set the focus, the cursor will always appear at the end.

$("#search-button").click(function (event) {
    event.preventDefault();
    $('#textbox').val('this');
    $("#textbox").focus();
    return false;
});

Here is the fiddle to test https://jsfiddle.net/5on50caf/1/


Still the intermediate variable is needed, (see var val=) else the cursor behaves strange, we need it at the end.

<body onload="document.getElementById('userinput').focus();">
<form>
<input id="userinput" onfocus="var val=this.value; this.value=''; this.value= val;"
         class=large type="text" size="10" maxlength="50" value="beans" name="myinput">
</form>
</body>

Try this, it has worked for me:

//input is the input element

input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.  

For the cursor to be move to the end, the input has to have focus first, then when the value is changed it will goto the end. If you set .value to the same, it won't change in chrome.


After hacking around with this a bit, I found the best way was to use the setSelectionRange function if the browser supports it; if not, revert to using the method in Mike Berrow's answer (i.e. replace the value with itself).

I'm also setting scrollTop to a high value in case we're in a vertically-scrollable textarea. (Using an arbitrary high value seems more reliable than $(this).height() in Firefox and Chrome.)

I've made it is as a jQuery plugin. (If you're not using jQuery I trust you can still get the gist easily enough.)

I've tested in IE6, IE7, IE8, Firefox 3.5.5, Google Chrome 3.0, Safari 4.0.4, Opera 10.00.

It's available on jquery.com as the PutCursorAtEnd plugin. For your convenience, the code for release 1.0 is as follows:

// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea

// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
    jQuery.fn.putCursorAtEnd = function()
    {
    return this.each(function()
    {
        $(this).focus()

        // If this function exists...
        if (this.setSelectionRange)
        {
        // ... then use it
        // (Doesn't work in IE)

        // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
        var len = $(this).val().length * 2;
        this.setSelectionRange(len, len);
        }
        else
        {
        // ... otherwise replace the contents with itself
        // (Doesn't work in Google Chrome)
        $(this).val($(this).val());
        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Google Chrome)
        this.scrollTop = 999999;
    });
    };
})(jQuery);

var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);

Simple. When editing or changing values, first put the focus then set value.

$("#catg_name").focus();
$("#catg_name").val(catg_name);

Still the intermediate variable is needed, (see var val=) else the cursor behaves strange, we need it at the end.

<body onload="document.getElementById('userinput').focus();">
<form>
<input id="userinput" onfocus="var val=this.value; this.value=''; this.value= val;"
         class=large type="text" size="10" maxlength="50" value="beans" name="myinput">
</form>
</body>

It's 2019 and none of the methods above worked for me, but this one did, taken from https://css-tricks.com/snippets/javascript/move-cursor-to-end-of-input/

_x000D_
_x000D_
function moveCursorToEnd(id) {_x000D_
  var el = document.getElementById(id) _x000D_
  el.focus()_x000D_
  if (typeof el.selectionStart == "number") {_x000D_
      el.selectionStart = el.selectionEnd = el.value.length;_x000D_
  } else if (typeof el.createTextRange != "undefined") {           _x000D_
      var range = el.createTextRange();_x000D_
      range.collapse(false);_x000D_
      range.select();_x000D_
  }_x000D_
}
_x000D_
<input id="myinput" type="text" />_x000D_
<a href="#" onclick="moveCursorToEnd('myinput')">Move cursor to end</a>
_x000D_
_x000D_
_x000D_


This problem is interesting. The most confusing thing about it is that no solution I found solved the problem completely.

+++++++ SOLUTION +++++++

  1. You need a JS function, like this:

    function moveCursorToEnd(obj) {
    
      if (!(obj.updating)) {
        obj.updating = true;
        var oldValue = obj.value;
        obj.value = '';
        setTimeout(function(){ obj.value = oldValue; obj.updating = false; }, 100);
      }
    
    }
    
  2. You need to call this guy in the onfocus and onclick events.

    <input type="text" value="Test Field" onfocus="moveCursorToEnd(this)" onclick="moveCursorToEnd(this)">
    

IT WORKS ON ALL DEVICES AN BROWSERS!!!!


For all browsers for all cases:

function moveCursorToEnd(el) {
    window.setTimeout(function () {
            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();
        }
    }, 1);
}

Timeout required if you need to move cursor from onFocus event handler


I've tried the following with quite great success in chrome

$("input.focus").focus(function () {
    var val = this.value,
        $this = $(this);
    $this.val("");

    setTimeout(function () {
        $this.val(val);
    }, 1);
});

Quick rundown:

It takes every input field with the class focus on it, then stores the old value of the input field in a variable, afterwards it applies the empty string to the input field.

Then it waits 1 milisecond and puts in the old value again.


el.setSelectionRange(-1, -1);

https://codesandbox.io/s/peaceful-bash-x2mti

This method updates the HTMLInputElement.selectionStart, selectionEnd, and selectionDirection properties in one call.

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange

In other js methods -1 usually means (to the) last character. This is the case for this one too, but I couldn't find explicit mention of this behavior in the docs.


I just found that in iOS, setting textarea.textContent property will place the cursor at the end of the text in the textarea element every time. The behavior was a bug in my app, but seems to be something that you could use intentionally.


I wanted to put cursor at the end of a "div" element where contenteditable = true, and I got a solution with Xeoncross code:

<input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">

<div id="test" contenteditable="true">
    Here is some nice text
</div>

And this function do magic:

 function pasteHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // non-standard and not supported in all browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = document.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}

Works fine for most browsers, please check it, this code puts text and put focus at the end of the text in div element (not input element)

https://jsfiddle.net/Xeoncross/4tUDk/

Thanks, Xeoncross


Set the cursor when click on text area to the end of text... Variation of this code is...ALSO works! for Firefox, IE, Safari, Chrome..

In server-side code:

txtAddNoteMessage.Attributes.Add("onClick", "sendCursorToEnd('" & txtAddNoteMessage.ClientID & "');")

In Javascript:

function sendCursorToEnd(obj) {
    var value =  $(obj).val(); //store the value of the element
    var message = "";
    if (value != "") {
        message = value + "\n";
     };
    $(obj).focus().val(message);
    $(obj).unbind();
 }

input = $('input'); 
input.focus().val(input.val()+'.'); 
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-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);}

_x000D_
_x000D_
document.querySelector('input').addEventListener('focus', e => {
  const { value } = e.target;
  e.target.setSelectionRange(value.length, value.length);
});
_x000D_
<input value="my text" />
_x000D_
_x000D_
_x000D_


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

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

Check this solution!

_x000D_
_x000D_
//fn setCurPosition_x000D_
$.fn.setCurPosition = function(pos) {_x000D_
    this.focus();_x000D_
    this.each(function(index, elem) {_x000D_
        if (elem.setSelectionRange) {_x000D_
            elem.setSelectionRange(pos, pos);_x000D_
        } else if (elem.createTextRange) {_x000D_
            var range = elem.createTextRange();_x000D_
            range.collapse(true);_x000D_
            range.moveEnd('character', pos);_x000D_
            range.moveStart('character', pos);_x000D_
            range.select();_x000D_
        }_x000D_
    });_x000D_
    return this;_x000D_
};_x000D_
_x000D_
// USAGE - Set Cursor ends_x000D_
$('#str1').setCurPosition($('#str1').val().length);_x000D_
_x000D_
// USAGE - Set Cursor at 7 position_x000D_
// $('#str2').setCurPosition(7);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p>Set cursor at any position</p>_x000D_
<p><input type="text" id="str1" value="my string here" /></p>_x000D_
<p><input type="text" id="str2" value="my string here" /></p>
_x000D_
_x000D_
_x000D_


Taking some of the answers .. making a single-line jquery.

$('#search').focus().val($('#search').val());

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