How to add a prototype for an input element?
I have an input element:
<input type="text" id="t" value="abcdefghij" /> I want to create selectionStart
document.getElementById("t").selectionStart I need functions:
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 to add this property to <input type="text" /> in IE? Is it possible?
Firstly, it is a bad idea, both in principle and in practice, to try to expand host objects. Host objects, such as DOM elements, can do pretty much what they like; in particular, they are not required to support what you are trying to do, and in IE <= 8, what you are targeting for this code, the DOM elements simply do not support this. Your options are either to use the function with which you pass the input element, or to create a wrapper object for each input that has the methods and properties that you need.
Secondly, your GetSelectionStart() and GetSelectionEnd() functions are erroneous: they will not process new lines correctly in text areas and have erroneous logic around lastIndexOf (what if the selected text appears more than once in the input?). I did a lot of work on this, and came up with what I am pretty sure is the best function to get input and select text fields in all the major browsers that I last posted here a couple of days ago: Is it possible to programmatically determine the position of the carriage in < input type = text> element?
You want to extend the HTMLInputElement interface, for example:
HTMLInputElement.prototype.selectionStart = … However, JavaScript experts consider this a bad practice .
These questions are also answered by:
Caret position in textarea, in characters from the start
Character Offset in Internet Explorer Text Box