I have pretty good function that do what I need, but in IE it doesn’t consider linebreaks and, maybe, some other stuff.
The function is next:
this.createSelection = function (field, start, end) {
if (field.createTextRange) {
var selRange = field.createTextRange();
selRange.collapse(true);
selRange.moveStart('character', start);
selRange.moveEnd('character', end - start);
selRange.select();
} else if (field.setSelectionRange) {
field.setSelectionRange(start, end);
} else if (field.selectionStart) {
field.selectionStart = start;
field.selectionEnd = end;
}
field.focus();
}
It needs to be modified in two points:
-
Highlight correct part of the text with linebreaks and other stuff.
-
Highlight not only inside textarea, but even in div, p, span etc.
Thanks for any help.
I’ve published a function many times on Stack Overflow that does this for textareas and text inputs, handling line breaks correctly. Here’s an example:
https://stackoverflow.com/a/3373056/96100
Doing the same for selections within regular HTML elements is trickier, and also less well-defined. Here’s an answer about this:
https://stackoverflow.com/a/9841644/96100