Skip to content Skip to sidebar Skip to footer

How Can I Tell If A Text Input Field Dom Node Does *not* Have A Selection With Javascript?

When I check inputFieldDomNode.selectionStart it always returns some number, even if it does not have a text selection and there's no caret in it. So how can I tell if it doesn't h

Solution 1:

At least window-globally, you can use Selection.isCollapsed

window.getSelection().isCollapsed

Despite the compatibility table, I have found it to be working in Chrome, and apparently it's been supported since IE 9 as well.

Solution 2:

You can check if a element is selected with something like:

document.getElementById("color-red").checked

which will return a boolean.

If that's what you want, check out an example at http://jsfiddle.net/o5t0ow9g/1/

Solution 3:

I think (but am not 100% sure) that if the element is not the active element for the document, it can't have a text selection. You can test it using document.activeElement:

if (inputFieldDomNode == document.activeElement) {
    // Do stuff with the selection
}

Example: http://jsfiddle.net/hpseuLj3/1/

Solution 4:

Ok I figured it out:

exports.getSelectionRange = function (element) {
    if(element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
        var selection = window.getSelection()
        for(var n=0; n<selection.rangeCount; n++) {
            varrange = selection.getRangeAt(0)
            if(range.startOffset === range.endOffset && range.startContainer.children[range.startOffset] === element /*|| range.startContainer === element || */) { // I don't think the input or textarea itself will ever be the startContainerreturn [element.selectionStart, element.selectionEnd]
            }
        }
        // else return undefined - the element doesn't have an active caret or active selection (it still may have an inactive selection)
    } else {
        // .. do something else unrelated to this question
    }
}

Basically, when you have an active text input, its parent is the range.startContainer and so you have to not only check that it is a child of range.startContaine but make sure that its the right child (the child that's selected) which is determined by the range.startOffset. Also, you have to make sure that input is the only thing that's selected, because its possible for the input to be included in a larger selection.

Note: I think this might still fail in cases where the actual input node is the only thing selected and not its contents. This is an incredibly rare edge case and i'm not sure if its even possible via user input (tho probably possible via the dom API).

Post a Comment for "How Can I Tell If A Text Input Field Dom Node Does *not* Have A Selection With Javascript?"