Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery selector and setSelectionRange is not a function

I have assembled a basic jfiddle below. For some reason my selector works to retrieve the textarea box to set the value, but the selector doesnt work to use the setSelectionRange function. On the console you'll find an error for .setSelectionRange is not a function.

http://jsfiddle.net/dMdHQ/6/

code(please refer to jfiddle): selector.setSelectionRange(carat,carat);

like image 846
srg2k5 Avatar asked Jun 18 '13 00:06

srg2k5


2 Answers

setSelectionRange(carat,carat) is not a method on jquery object. You want to use it on DOM element. So try:

selector[0].setSelectionRange(carat,carat); //use `[0]` or .get(0) on the jquery object

See Reference

Fiddle

like image 150
PSL Avatar answered Oct 15 '22 13:10

PSL


For me this is a good solution

selector[0].setSelectionRange(start ,end); 

But I would like to add one more thing. I noticed that setSelectionRange is something that becomes available asynchronously after the element gets focus.

var element = selector[0];
element.addEventListener('focus', function() {
   element.setSelectionRange(start, end); 
});
element.focus();

Also you can use alternatively:

element.selectionStart = start;
element.selectionEnd = end;
like image 3
Prusdrum Avatar answered Oct 15 '22 14:10

Prusdrum