|
||||||||||||||||||||||||
|
How to programmatically highlight text or select text in multiline text-area on IE
on Mozilla/Firefox there is this simple text-area object method called setSelectionRange() which easily takes care of that.
However on IE (at least up to IE6) there is no easy way to do that reliably. To do it you would have to juggle around with text ranges; these are IE proprietary animals and are objects that enclose and control portions of text on the page.
When the Input text that you want to manipulate is multiline (as in a multiline <textarea> element) the situation becomes more complicates as new lines are recorded as ASCII Decimal 13,10 char sequances that both count towards the total number of chars in the range's text string, while on the other hand textrange methods like moveStart() and moveEnd() do not seem to be counting them when moving textrange endpoints!
To get out of this mess I had to code the following two JS functions (you can see them at work - and they seem to be working well - on this page, as they take care of the hiliting of the text matched by the RegEx).
The first one gets you the number of linebreaks in the passed string. The other juggles around in order to select/highlight text in the passed text-area, between indexes i and j. The fourth parameter is not used currently.
I use the word "juggle" because some range methods (e.g. moveEnd()) do not work well or as expected, at least in some cases. The only reliable way I have found to do multiline highliting is to get the full text-area's text range, duplicate it thrice, and then moveStart of the first and second duplicates to i and j respectively. I then setEndPoint twice on the third duplicate in order to enclose the text range section between i and j. I then select that third duplicate.
function calculateLines(s){
var count = 0;
for (var i = 0; i < s.length-1; i++){
if (s.charCodeAt(i) == 13 && s.charCodeAt(i+1) == 10) count++;
}
return count;
}
function hiliteTA(ta,i,j,s){
// Compensation is needed because the regex string subscripts include newline chars,
// while the range's moveStart() and moveEnd() do not
var compensation1 = calculateLines(ta.value.substring(0,i));
var compensation2 = calculateLines(ta.value.substring(0,j));
var r = ta.createTextRange();
var r1,r2,r3;
r1 = r.duplicate();
r1.moveStart("character", i - compensation1);
//alert(r1.text);
r2 = r.duplicate();
r2.moveStart("character", j - compensation2);
//alert(r2.text);
r3 = r.duplicate();
//r3.collapse();
r3.setEndPoint("StartToStart", r1);
r3.setEndPoint("EndToStart", r2);
r3.select();
}




Post new comment