3

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

Daniel LeCheminant
  • 50,583
  • 16
  • 120
  • 115
Alex
  • 4,122
  • 5
  • 34
  • 40
  • I believe this is a duplicate of http://stackoverflow.com/questions/235411/is-there-an-internet-explorer-approved-substitute-for-selectionstart-and-selectio/235582 – Daniel LeCheminant Feb 24 '09 at 22:33

2 Answers2

5

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
        }
}
Community
  • 1
  • 1
Daniel LeCheminant
  • 50,583
  • 16
  • 120
  • 115
0
  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 
    }
   }
  }