I have a textarea and a button on a form. The textarea may already have some text in it. I would like the cursor to move to the last position in the text area when the button is clicked.
Is this possible?
I have a textarea and a button on a form. The textarea may already have some text in it. I would like the cursor to move to the last position in the text area when the button is clicked.
Is this possible?
By “the last position”, do you mean the end of the text?
Changing the ‘.value’ of a form field will move the cursor to the end in every browser except IE. With IE you have to get your hands dirty and deliberately manipulate the selection, using non-standard interfaces:
Or do you mean put the cursor back to the place it was previously, the last time the textarea was focused?
In every browser except IE, this will already happen just by calling ‘element.focus()’; the browser remembers the last cursor/selection position per input and puts it back on focus.
This would be quite tricky to reproduce in IE. You would have to poll all the time to check where the cursor/selection was, and remember that position if it was in an input element, then fetch the position for a given element when the button was pressed and restore it. This involves some really quite tedious manipulation of ‘document.selection.createRange()’.
I'm not aware of anything in jQuery that would help you do this, but there might be a plugin somewhere perhaps?
To set mouse focus and move cursor to end of input. Its work in every browser, Its just simple logic here.
I modified @mkaj extension a little to support default value
xgMz's answer was best for me. You don't need to worry about the browser:
And here's a quick jQuery extension I wrote to do this for me next time:
Use like this:
You can also do this:
This code works for both
input
andtextarea
. Tested with latest browsers: Firefox 23, IE 11 and Chrome 28.jsFiddle
available here: http://jsfiddle.net/cG9gN/1/Source: https://stackoverflow.com/a/12654402/114029
You could use this https://github.com/DrPheltRight/jquery-caret