Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selectionStart-End with textareas

I'm having this annoying problem, I can't seem to get the starting and ending index of the selected text in a textarea, all I get is undefined like this:

$('#myarea').selectionStart; // return undefined 

Did I do something wrong?

like image 290
Dennis Avatar asked Apr 03 '09 17:04

Dennis


2 Answers

Try:

$('#myarea')[0].selectionStart; 

Why? A jQuery selector does not return the actual DOM elements but the wrapped jQuery collection. jQuery makes the actual DOM elements accessible as an array, so if you wanted to use the 1st matched element (and in this case, the only one, since it's by ID), you would do the above.

like image 91
Paolo Bergantino Avatar answered Sep 25 '22 23:09

Paolo Bergantino


Since jQuery version 1.6, you can use .prop() method:

Get:

// always start at 0  var start = $('#myarea').prop('selectionStart'); var end = $('#myarea').prop('selectionEnd'); 

Set:

$('#myarea').prop('selectionStart', 10); $('#myarea').prop('selectionEnd', 15);  // or short hand by  $('#myarea').prop({     'selectionStart': 10,     'selectionEnd': 15 }); 
like image 44
Tân Avatar answered Sep 24 '22 23:09

Tân