I have been trying to select text in a textarea programatically based on start and end indexes, but for some reason the selection is offset by a few character locations:

My users make an initial manual selection that I store to a database. To get the start/end positions of the initial selection I am using the approach outlined here Caret position in textarea, in characters from the start (Answered by Tim Down)

I store the selections made by the users, and when they come back to the page I want to default in their previous selections.

My code for making the selection based on the stored positions I extracted using Tim Down's function is the following:

  function SelectText(start,end) {
    var textArea = document.getElementById("textArea");

    var inputRange = textArea.createTextRange();
    inputRange.collapse(true);

    inputRange.moveStart("character", start);
    inputRange.moveEnd("character", end - start);

    inputRange.select();
}

It seems like the issue is caused by linebreaks/spaces. Does anyone know how to correctly make selections in IE programatically based on start and end?

有帮助吗?

解决方案

I don't know exactly if it will help you but you can try to use RangyInputs js library which was developed by Tim Down and available using the following url: http://code.google.com/p/rangyinputs/

As for me I used Rangy (which is developed by Tim Down too) library for content editable div on one of my projects and it really works well and helped me a lot.

The documentation about supported methods you can find on WiKi page: http://code.google.com/p/rangyinputs/wiki/Documentation

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top