views:

323

answers:

2

In Firefox, you can simply call:

myInputTextField.selectionStart or myInputTextField.selectionEnd

to get the first and last indices of the selected text in the input box.

In IE, I know that you can call document.selection.createRange() to fiddle with the selection a little bit. For the life of me, however, I have not found any value that represents that character offset within the selection.

Am I missing something? Is there any way to get the same value in IE?

Thank you!

Alex

+3  A: 

A direct quote from a previous response to a very similar question that will get you a selection range:

function getSelection(inputBox) {
        if ("selectionStart" in inputBox) {
                return {
                        start: inputBox.selectionStart,
                        end: inputBox.selectionEnd
                }
        }

        //and now, the blinkered IE way
        var bookmark = document.selection.createRange().getBookmark()
        var selection = inputBox.createTextRange()
        selection.moveToBookmark(bookmark)

        var before = inputBox.createTextRange()
        before.collapse(true)
        before.setEndPoint("EndToStart", selection)

        var beforeLength = before.text.length
        var selLength = selection.text.length

        return {
                start: beforeLength,
                end: beforeLength + selLength
        }
}
Daniel LeCheminant
A: 
  getSelectionOffset : function(argObject) {
   if (typeof(argObject.contentWindow.getSelection) != 'undefined') { //Moz
    return {
     start: argObject.contentWindow.getSelection().getRangeAt(0).selectionStart,
     end: argObject.contentWindow.getSelection().getRangeAt(0).selectionEnd
    }
   }
   if (document.selection && document.selection.createRange) { //IE
    var allText = argObject.contentWindow.document.selection.createRange().parentElement().innerText;
    var selText = argObject.contentWindow.document.selection.createRange().text;
    return {
     start: allText.indexOf(selText),
     end: allText.indexOf(selText) + selText.length 
    }
   }
  }