javascripttextareayui

Selecting a specific subsection of a text input box in Javascript/YUI


I'm trying to programmatically select a substring of text inside of an input text box. I found an example here but there's only one problem. It doesn't work! I tried it on FF4, the latest build of Chrome and IE. I haven't tried Opera but if it's not working on those 3 it's not a good enough solution.

I also searched on setSelectionRange to see if it's deprecated but I couldn't find anything to lead me to believe that it was.

Here's my code that I'm trying to implement this in:

_defShowTimeUnitFn: function(e) {
    if(!this.isValidInput()) {
        var inputNode = this._inputNode,
            input     = inputNode.get(VALUE),
            newText;


        newText = Y.Lang.trim(input) + ' ' + SHOW_TIMEUNIT_DEFAULT;
        inputNode.set(VALUE, newText);

        if (inputNode.setSelectionRange) {
            // Mozilla
            inputNode.setSelectionRange(0, 1);
        } else if (inputNode.createTextRange) {
            // IE
            var range = inputNode.createTextRange();
            range.collapse(true);
            range.moveEnd('character', 1);
            range.moveStart('character', 1);
            range.select();
        } else if (inputNode.selectionStart) {
            inputNode.selectionStart = 0;
            inputNode.selectionEnd = 1;
        }

        inputNode.focus();
    }
},

Does anybody know the commands to accomplish

textbox.setSelectionRange(start,end);

in a modern browser?


Solution

  • setSelectionRange() works on all major browsers except IE <= 8. Since get() and set() are not standard methods of DOM elements, I'm pretty sure inputNode is not a reference to an actual <input> element. I imagine it's a YUI wrapper object around an <input> element. You need to call setSelectionRange() on the input itself rather than the YUI wrapper object.