7

I have a input element:

<input type="text" id="t" value="abcdefghij" />

I want to create a selectionStart

document.getElementById("t").selectionStart

The functions I need are:

function GetSelectionStart(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveEnd('character', o.value.length)
        if (r.text == '') return o.value.length
        return o.value.lastIndexOf(r.text)
    } else return o.selectionStart;
}

function GetSelectionEnd(o) {
    if (o.createTextRange) {
        var r = document.selection.createRange().duplicate()
        r.moveStart('character', -o.value.length)
        return r.text.length
    } else return o.selectionEnd;
}

How can I add this "property" to <input type="text" /> on IE? Is it possible?

BrunoLM
  • 97,872
  • 84
  • 296
  • 452

3 Answers3

4

You'll want to extend the HTMLInputElement interface, like this:

HTMLInputElement.prototype.selectionStart = …

However, JavaScript experts consider this a bad practice.

Marcel Korpel
  • 21,536
  • 6
  • 60
  • 80
4

First, it's a bad idea both in principle and in practice to try extend host objects. Host objects such as DOM elements can do pretty much what they like; in particular, they are not obliged to support what you're trying to do and in IE <= 8, which is what you're targetting with this code, DOM elements simply don't support this. Your options are either to use a function to which you pass an input element, or create a wrapper object for each input that has the methods and properties you need.

Second, your GetSelectionStart() and GetSelectionEnd() functions are flawed: they will not handle new lines correctly in textareas and have faulty logic around lastIndexOf (what if the selected text appears more than once in the input?). I've done quite a lot of work on this, and have come up with what I'm fairly convinced is the best function around for getting input and textarea selections in all major browsers, which I last posted here a couple of days ago: Is it possible to programmatically detect the caret position within a <input type=text> element?

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • I was just trying to fix the damn IE. Those functions I just copied from some article http://www.google.com/search?ie=UTF-8&oe=UTF-8&sourceid=navclient&gfns=1&q=IE+selectionstart. Thanks for pointing these flaws and for providing a reliable function. I guess I have no choice, I will have to use a method instead... – BrunoLM Nov 17 '10 at 18:04
0

This is also answered in these questions:

Caret position in textarea, in characters from the start

Character offset in an Internet Explorer TextRange

Community
  • 1
  • 1
Sean
  • 4,365
  • 1
  • 27
  • 31