Richard Nichols
Richard Nichols

Reputation: 1940

How to select a character range in a textarea using Javascript?

Simple question - is there any way to select a sub-set of the text displayed in a <textarea> control using Javascript?

e.g. have a function like

selectText(startCharNo, endCharNo, textareaName);

It also needs to be IE6 compatible.

Upvotes: 0

Views: 3818

Answers (3)

Mike
Mike

Reputation:

selectText(startCharNo, endCharNo, textAreaName){
   var content = document.getElementById(textAreaName).innerHTML; //value may work too
   var piece = content.subString(startCharNo, endCharNo);
   return piece;
}

Upvotes: 0

Rafael
Rafael

Reputation: 18522

yes, it is possible

element.focus();
if(element.setSelectionRange)
   element.setSelectionRange(startCharNo, endCharNo);
else {
   var r = element.createTextRange();
   r.collapse(true);
   r.moveEnd('character', endCharNo);
   r.moveStart('character', startCharNo);
   r.select();   
}

element is the reference to the textarea

Upvotes: 6

NinethSense
NinethSense

Reputation: 9028

createTextRange()

http://www.developerfusion.com/forum/thread/48987/

Upvotes: 0

Related Questions