Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Set Cursor Position in Text Area

How do you set the cursor position in a text field using jQuery? I've got a text field with content, and I want the users cursor to be positioned at a certain offset when they focus on the field. The code should look kind of like this:

$('#input').focus(function() {   $(this).setCursorPosition(4); }); 

What would the implementation of that setCursorPosition function look like? If you had a text field with the content abcdefg, this call would result in the cursor being positioned as follows: abcd**|**efg.

Java has a similar function, setCaretPosition. Does a similar method exist for javascript?

Update: I modified CMS's code to work with jQuery as follows:

new function($) {   $.fn.setCursorPosition = function(pos) {     if (this.setSelectionRange) {       this.setSelectionRange(pos, pos);     } else if (this.createTextRange) {       var range = this.createTextRange();       range.collapse(true);       if(pos < 0) {         pos = $(this).val().length + pos;       }       range.moveEnd('character', pos);       range.moveStart('character', pos);       range.select();     }   } }(jQuery); 
like image 200
jcnnghm Avatar asked Jan 31 '09 16:01

jcnnghm


People also ask

How to set cursor position in textbox in jQuery?

The code should look kind of like this: $('#input'). focus(function() { $(this). setCursorPosition(4); });

How do I change the cursor position in textarea?

To set the cursor at the end of a textarea: Use the setSelectionRange() method to set the current text selection position to the end of the textarea. Call the focus() method on the textarea element. The focus method will move the cursor to the end of the element's value.


1 Answers

Here's a jQuery solution:

$.fn.selectRange = function(start, end) {     if(end === undefined) {         end = start;     }     return this.each(function() {         if('selectionStart' in this) {             this.selectionStart = start;             this.selectionEnd = end;         } else if(this.setSelectionRange) {             this.setSelectionRange(start, end);         } else if(this.createTextRange) {             var range = this.createTextRange();             range.collapse(true);             range.moveEnd('character', end);             range.moveStart('character', start);             range.select();         }     }); }; 

With this, you can do

$('#elem').selectRange(3,5); // select a range of text $('#elem').selectRange(3); // set cursor position 
  • JsFiddle
  • JsBin
like image 180
mpen Avatar answered Sep 22 '22 19:09

mpen