406

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?

Peanut
  • 18,967
  • 20
  • 72
  • 78

36 Answers36

253

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)

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

Using Vanilla JS (borrowing addEvent function from this answer)

// Basic cross browser addEvent
function addEvent(elem, event, fn){
if(elem.addEventListener){
  elem.addEventListener(event, fn, false);
}else{
  elem.attachEvent("on" + event,
  function(){ return(fn.call(elem, window.event)); });
}}
var element = document.getElementById('el');

addEvent(element,'focus',function(){
  var that = this;
  setTimeout(function(){ that.selectionStart = that.selectionEnd = 10000; }, 0);
});
<input id='el' type='text' value='put cursor at end'>

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.

Community
  • 1
  • 1
Gary
  • 13,303
  • 18
  • 49
  • 71
  • 2
    worked for me in Chrome 24.0.1312.57, IE 9.0.8112 and Firefox 18.0.2 – Chris - Haddox Technologies Feb 14 '13 at 14:55
  • 4
    This is a good solution instead of an observation (kludge), is less code, and is more understandable then the alternatives discussed here. Thanks. – Derek Litz Mar 27 '13 at 19:00
  • I would rather do that only for the first focus event, and call it right away. Otherwise, everytime you click in the field, the cursor will be moved to the end. – Damien Apr 15 '13 at 12:01
  • `this.selectionStart = this.selectionEnd = 0; ` this should move the focus before the first letter of the input box. But rather, when I debugged it's not even changing the value of selectionEnd and selectionStart! And also not moving it to the first character!! – soham Sep 19 '13 at 08:26
  • Setting it to 0 works for me, what browser are you using? Remember, you have to call this after focus has been applied to the element. – Gary Sep 19 '13 at 18:49
  • In response to @Damien's comment: `onfocus="var t=this; if(!t.selectionStart) t.selectionStart = t.selectionEnd = t.value.length;"`, which will let you click in the middle, but still start at the end. One caveat: if you click at the beginning, it'll force at the end. For that, you'd have to create an onclick event, preventDefault, and manually setting the position to the front (or where it would be clicked) -- more work than is necessary for this comment. – vol7ron Sep 29 '15 at 23:05
  • 1
    Opera was beening reported to work incorrectly sometimes with `selectionStart` and `length` returning smaller number on spaces. That's why I use `10000` or any other big enough number instead of `this.value.length` (tested on IE8 and IE11) – vladkras Nov 02 '15 at 20:15
  • For the jQuery answer: using ES6 you can use an arrow function so you don't have to define that. –  Jun 03 '16 at 18:41
  • This was not working on Chrome so I just added `input.focus();` before this and it worked across IE and Chrome for me. – lbrahim Aug 26 '16 at 15:26
  • Yeah, chrome is a little quarky with its focus. Did the setTimeout variant not work for you either? If not, what version are you using? – Gary Aug 26 '16 at 15:35
  • What exactly is `this` in the context of your code? – vsync Aug 19 '18 at 17:32
  • `this` is the text input; that code would be in the function attached to the event listener. – Gary Aug 20 '18 at 13:14
  • 1
    Doesn't seem to work on `contenteditable` elements (not inputs) – vsync Nov 15 '18 at 23:00
207

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.

sth
  • 222,467
  • 53
  • 283
  • 367
chenosaurus
  • 2,263
  • 1
  • 14
  • 6
  • 2
    This is like onfocus="this.value = this.value; – Tareq Oct 21 '10 at 06:17
  • 18
    Setting the focus before setting the value is the key to get it work in Chrome. – anatoly techtonik May 19 '11 at 11:39
  • 11
    Why put `this.` in front of input on lines 2, 3, and 4? We already know that `input` is the input element. Using `this` seems redundant. Good solution otherwise! – The111 Jul 23 '12 at 23:25
  • 4
    @Tareq They are not the same. This trick is much better than the accepted answer. – Lewis Jun 15 '14 at 08:51
  • This worked in Safari 8.0.5 whereas none of the other tricks (except JQuery plugins) have succeeded. – Joseph Hansen Apr 13 '15 at 08:24
  • This one worked in the latest Chrome! Important part was to set it to an empty string first. Thanks! – Larry Lawless Nov 22 '16 at 13:49
  • This won't scroll to the end of the input for me in latest chrome. I [found out](http://stackoverflow.com/a/17375618/552067) I needed `inputEl.scrollLeft = inputEl.scrollWidth;`. – Web_Designer Apr 26 '17 at 02:01
  • 4
    Easier: `$input.focus().val($input.val());` – milkovsky May 08 '17 at 15:02
  • Does anyone know why using "this" and "input"? I used: input.focus(); var value = input.value; input.value = ''; input.value = value; And it worked perfectly! Itested with IE7, Chrome, Firefox. – aldemarcalazans May 30 '17 at 17:45
  • 1
    Works great — however in Chrome 61 the cursor doesn't flicker as usual until you manually focus the field again. Any idea what's going on? – RooWM Oct 08 '17 at 02:12
  • Bad side effects: this will activate OnChange() events. – jacouh Mar 18 '19 at 14:06
  • @Tareq it is not: `a = a` is undefined behavior: UA can do nothing instead of rewriting the value, so the side effect of moving cursor may not happen. See comments below Mike Berrow's answer. – Jan Turoň Apr 27 '22 at 10:00
  • in chrome android, if input size is small, value not moving – Anas Fanani Nov 23 '22 at 14:48
190

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 but doesn't work in modern browsers (see comments) as it is not specified that UA must overwrite the value in this case (edited in accordance with meta policy).

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169
Mike Berrow
  • 2,546
  • 1
  • 20
  • 16
100

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);
teedyay
  • 23,293
  • 19
  • 66
  • 73
  • 6
    Why calculate the length? Why not just this.setSelectionRange(9999,9999) if you are going to overshoot it anyway? – PRMan Oct 31 '15 at 17:52
28
<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

Hallgeir Engen
  • 841
  • 9
  • 10
22

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/

function moveCursorToEnd(id) {
  var el = document.getElementById(id) 
  el.focus()
  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();
  }
}
<input id="myinput" type="text" />
<a href="#" onclick="moveCursorToEnd('myinput')">Move cursor to end</a>
Andy Raddatz
  • 2,792
  • 1
  • 27
  • 29
19

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.

seeker_of_bacon
  • 1,939
  • 2
  • 19
  • 20
19

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.

Hejner
  • 372
  • 3
  • 15
  • 1
    perfect! All other's solutions are not work for me, only your solution is working for me. Maybe because I am using php to assign value to textarea, and js cannot detect the value so js must wait for 1 millisecond. – zac1987 Jan 15 '12 at 21:18
  • 3
    @zac1987 that's probably not the case as php would render the html, the html would be loaded to the client and then the js would run. Chances are you're not waiting for a document ready event. – reconbot Jul 17 '12 at 13:45
  • Just to point out that using setTimeout like that can be a cause of unpredictable result. The code could behave correctly in some circumstances like sometimes something could change the input during that 1ms that the val won't be set back. Also it's important to note that 1ms second is the minimum waiting time. So if you have some cpu bound methods, the focus might wait more than 1ms. This will make the UI unresponsive. And it shouldn't be necessary as the .val() method should trigger UI changes anyway. – Loïc Faure-Lacroix Apr 20 '18 at 19:43
11

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

$("#catg_name").focus();
$("#catg_name").val(catg_name);
Gary
  • 13,303
  • 18
  • 49
  • 71
Arun Prasad E S
  • 9,489
  • 8
  • 74
  • 87
9

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>
sth
  • 222,467
  • 53
  • 283
  • 367
Adrian
  • 91
  • 1
  • 2
8
const end = input.value.length

input.setSelectionRange(end, end)
//  scroll to the bottom if a textarea has long text
input.focus()
Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
7

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()
Kishore Newton
  • 156
  • 2
  • 6
5

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

terma
  • 1,199
  • 1
  • 8
  • 15
  • note that this causes problems on Android, though, as the range selection puts data into the keyboard buffer, which means that any key you type will end up duplicating the text in the input, which is not the most useful. – Mike 'Pomax' Kamermans Jun 12 '15 at 19:56
  • 1
    This is amazing and worked awesome for me in ie! I have a bunch of inputs that need a scrollLeft and that does weird things in ie so I was looking for something that I could use for a shim and this was it. It doesn't work in other browsers, but for ie where nothing works this is amazing! – zazvorniki Mar 08 '16 at 16:38
5

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"/>
Konrad G
  • 419
  • 7
  • 14
  • 1
    This is the solution that actually works on Chrome for me now. The syntax is weird but hey, will learn to live with this solution for now! – Sam Bellerose Nov 02 '18 at 18:32
5

document.querySelector('input').addEventListener('focus', e => {
  const { value } = e.target;
  e.target.setSelectionRange(value.length, value.length);
});
<input value="my text" />
hjrshng
  • 1,675
  • 3
  • 17
  • 30
3

In jQuery, that's

$(document).ready(function () {
  $('input').focus(function () {
    $(this).attr('value',$(this).attr('value'));
  }
}
sth
  • 222,467
  • 53
  • 283
  • 367
Anonymous
  • 31
  • 1
  • 3
    This function will only assign the value attribute to value when $('input') receives focus. It won't send the cursor to the end of the line. – vrish88 May 15 '10 at 06:48
3

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!!!!

Gary
  • 13,303
  • 18
  • 49
  • 71
3

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.

Gary
  • 13,303
  • 18
  • 49
  • 71
Joey Guerra
  • 596
  • 6
  • 11
2
var valsrch = $('#search').val();
$('#search').val('').focus().val(valsrch);
HanKrum
  • 59
  • 5
  • What does this solution do better than the existing jQuery solution? – Rovanion May 21 '16 at 07:54
  • This is another solution. If you not have permition to redact html files and only javascript, this solution is betther ;) I had same situation! – HanKrum May 21 '16 at 12:23
  • this solution worked for me the other jQuery solution didn't probably it related to the fact you empty the input value before focus it. – talsibony Oct 30 '17 at 10:28
2

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

$('#search').focus().val($('#search').val());
Ravi Ram
  • 24,078
  • 21
  • 82
  • 113
1

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.

Decko
  • 18,553
  • 2
  • 29
  • 39
1

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.

l.varga
  • 851
  • 6
  • 14
1

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

inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;
Elijah
  • 1,814
  • 21
  • 27
0

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/

Usman Shaukat
  • 1,315
  • 16
  • 22
0

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

Lexsoul
  • 155
  • 2
  • 8
0

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.

amku91
  • 1,010
  • 11
  • 21
0

Check this solution!

//fn setCurPosition
$.fn.setCurPosition = function(pos) {
    this.focus();
    this.each(function(index, elem) {
        if (elem.setSelectionRange) {
            elem.setSelectionRange(pos, pos);
        } else if (elem.createTextRange) {
            var range = elem.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    });
    return this;
};

// USAGE - Set Cursor ends
$('#str1').setCurPosition($('#str1').val().length);

// USAGE - Set Cursor at 7 position
// $('#str2').setCurPosition(7);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Set cursor at any position</p>
<p><input type="text" id="str1" value="my string here" /></p>
<p><input type="text" id="str2" value="my string here" /></p>
Roberto Godoy
  • 185
  • 1
  • 2
  • 8
0

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();
 }
linuts
  • 6,608
  • 4
  • 35
  • 37
shirlymp
  • 9
  • 2
0

I took the best answers from here, and created a function that works well in Chrome.

  1. You will need to wrap the logic in a timeout, because you have to wait for the focus to finish before accessing the selection
  2. To place the cursor at the end, the selection start needs to be placed at the end
  3. In order to scroll to the end of the input field, the scrollLeft needs to match the scrollWidth

/**
 * Upon focus, set the cursor to the end of the text input
 * @param {HTMLInputElement} inputEl - An HTML <input> element
 */
const setFocusEnd = (inputEl) => {
  setTimeout(() => {
    const { scrollWidth, value: { length } } = inputEl;
    inputEl.setSelectionRange(length, length);
    inputEl.scrollLeft = scrollWidth;
  }, 0);
};

document
  .querySelector('input')
  .addEventListener('focus', (e) => setFocusEnd(e.target));
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
}

body {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

input:focus {
  background-color: hsla(240, 100%, 95%, 1.0);
}
<div>Click anywhere in the field</div>
<input
  type="text"
  placeholder="Search..."
  value="This is some really, really long text">
cssyphus
  • 37,875
  • 18
  • 96
  • 111
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0
<input id="input_1">
<input id="input_2" type="hidden">

<script type="text/javascript">
//save input_1 value to input_2
$("#input_2").val($("#input_1").val());

//empty input_1 and add the saved input_2 into input_1
$("#input_1").val("").val($("#input_2").val()).focus();
</script>
Dexter
  • 74
  • 8
-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;
}
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
-1

Try the following code:

$('input').focus(function () {
    $(this).val($(this).val());
}).focus()
msroot
  • 817
  • 11
  • 13
  • 1
    Is adding trailing whitespace a side effect the OP has indicated they desire? – Charles Duffy Mar 09 '15 at 20:55
  • But why my answer get -2? I dont get it! This is examples it works – msroot Mar 09 '15 at 21:55
  • 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. – Charles Duffy Mar 09 '15 at 21:59
  • 1
    (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). – Charles Duffy Mar 09 '15 at 22:00
  • 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". – Charles Duffy Mar 09 '15 at 23:53
  • I found this answer helpful and works just fine cross multiple browsers: stackoverflow.com/a/19568146/936468 – Simon Mbatia Oct 13 '16 at 12:58
-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);}
sth
  • 222,467
  • 53
  • 283
  • 367
shirlymp
  • 9
  • 2
-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();
    }
}
Mahfuzur Rahman
  • 1,497
  • 18
  • 23
-2

Well, I just use:

$("#myElement").val($("#myElement").val());
Peter O.
  • 32,158
  • 14
  • 82
  • 96
-2
input = $('input'); 
input.focus().val(input.val()+'.'); 
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}
Brynner Ferreira
  • 1,527
  • 1
  • 21
  • 21