3

Consider the following example: (demo here)

HTML:

<input type="text" />
<div>Click here to set focus</div>

JS:

$(function() {
    $("input").val("Hello");
    $("div").click(function() {
        $("input").focus();
    });
});

When the div is clicked, the cursor positioned at the beginning of the text: |Hello.

How could I set the cursor at the end of the text: Hello| ?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • its already setting to end of the string maybe cause of your browser i am using firefox and I just tried your demo link and it works. When i click the div , the cursor setting end of hello – Sedat Başar Sep 26 '11 at 07:16
  • even for me, with chrome, it comes at the end of string. – rtdp Sep 26 '11 at 07:17
  • It works in chrome also. Unless I position the cursor to somewhere else, of course, but by default it goes to the end. – willdanceforfun Sep 26 '11 at 07:18
  • for IE the cursor is positoned at the beginning of the text – yb007 Sep 26 '11 at 07:26
  • I use Firefox 6.0.2, and when I click on the `div` in the example above, the cursor is positioned at the beginning of `Hello`. – Misha Moroshko Sep 26 '11 at 12:27
  • In Chrome 14.0, the cursor is positioned at the end though. – Misha Moroshko Sep 26 '11 at 12:28
  • This question looks like a duplicate of http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element –  Jul 14 '16 at 12:15

2 Answers2

1

Use this plugin: http://plugins.jquery.com/project/PutCursorAtEnd

Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • 3
    You don't need a goddamn plugin for everything! – HyderA Sep 26 '11 at 07:31
  • Here's the [plugin code](http://plugins.jquery.com/files/jquery.putCursorAtEnd.1.0.js.txt), take what you need and implement it the right way. – HyderA Sep 26 '11 at 07:35
  • I think using the plugin is a good idea, because if the plugin is updated (for example to cater for new browsers that don't exist yet) then you can easily update all your sites that use the plugin. – Billy Moon Sep 26 '11 at 09:27
  • Up until that time, your users have to make tonnes of extra http requests to download the tonnes of plugins you've pointed to. All because you couldn't write a simple function yourself. If the plugin code gets updated, update your own damn code. – HyderA Sep 26 '11 at 10:40
  • You could write some code to concatenate your plugins into one file that gets minified and compressed, which solves your issue of multiple downloads... and also your issue with wanting people to write code – Billy Moon Sep 26 '11 at 13:21
  • Link to plugin is now broken. – david Jan 13 '15 at 00:30
  • Not tried it out, but this seems thorough: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/ – Billy Moon Jan 13 '15 at 01:25
0

I think you are looking for selectionStart.

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180