简体   繁体   中英

Javascript setSelectionRange in unit tests not behaving as expected

I'm using the qunit framework for unit testing interactions with an HTML that I have created programmatically using jquery (ie, 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?

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().

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM