Javascript setSelectionRange in unit tests not behaving as expected

1.1k views Asked by At

I'm using the qunit framework for unit testing interactions with an HTML that I have created programmatically using jquery (i.e., var $textarea = $('')) in Chrome. Here is the code I am using to update the selection in the textarea.

    TextAreaView.prototype.setSelectionOffsets = function(cursor) {
    var input = this.$textarea.get(0);
    if (!input.setSelectionRange) {
        return;
    }
    if (cursor.start <= input.value.length && cursor.end <= input.value.length) {
        input.focus();
        input.setSelectionRange(cursor.start, cursor.end, "forward");
    }
}

I have verified that I am calling this method with 0 < cursor.start == cursor.end < input.value.length.

When I step through with the debugger, everything appears ok - but after it hits the "input.setSelectionRange" line, inspection of the input element shows that the selectionEnd and selectionStart properties=0, the selectionDirection="none"

I'm very confused as to what is happening here. I've read Mozilla's documentation on textarea elements, and I believe my call to setSelectionRange is valid. Could this somehow be related to the fact that I have created the textarea programmatically and that it is not actually being displayed?

1

There are 1 answers

0
tronbabylove On BEST ANSWER

Found the answer to this as I was typing the question, so I figured I would share for anyone who may stumble upon this. The answer was obvious, I basically hit upon in my last sentence: I was creating a textarea DOM element with $('') and storing that object, but I never inserted that object into the document. After I appended the element to the body, setSelectionRange updates the selection as expected. In my situation, it isn't really desirable to display the actual textarea on my unit test results page, but this is easily fixed with a call to $textarea.hide().