Friday, May 18, 2012

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?



Source: Tips4all

11 comments:

  1. 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

    ReplyDelete
  2. 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);

    ReplyDelete
  3. 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.

    ReplyDelete
  4. <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

    ReplyDelete
  5. Have a look at this article. It describes how to change text within an input or textarea element, but you can also use it to move the cursor.

    ReplyDelete
  6. 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>

    ReplyDelete
  7. 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.

    ReplyDelete
  8. In jQuery, that's

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

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

    $("input.focus").focus(function () {
    var val = this.value;
    var $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.

    ReplyDelete
  10. There's a much simpler way to accomplish this (although I doubt many will see this answer buried within the rest).

    $(element).focus(function(){
    //I used jQuery to set the listener, but it's not necessary otherwise
    this.selectionStart = this.selectionEnd = this.value.length;
    });

    ReplyDelete
  11. 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);}

    ReplyDelete