How to know if the text in a textbox is selected?

I have text boxes <input type='text'> that only allow numeric characters and wont let the user enter a dot (.) more than once. Problem is, if the text in the text box is selected, the user intends to overwrite the contents with a dot, hence making it allowed! The question is, how can you tell in javascript whether the text in that text box is selected or not.

Thanks


Solution 1:

The following will tell you whether or not all of the text is selected within a text input in all major browsers.

Example: http://www.jsfiddle.net/9Q23E/

Code:

function isTextSelected(input) {
    if (typeof input.selectionStart == "number") {
        return input.selectionStart == 0 && input.selectionEnd == input.value.length;
    } else if (typeof document.selection != "undefined") {
        input.focus();
        return document.selection.createRange().text == input.value;
    }
}

Solution 2:

2017 Specific Answer - Faced the same issue recently.

We were allowing users to enter only 3 digits at a time. When the user tried to enter the fourth character we returned false.

This became an issue when the user had a selection and was trying to overwrite the values.

Taking a hint from Tim's answer. I understood that I wanted to see if the selection value was same as the input's value.

In modern browsers I achieved it by doing:

document.getSelection().toString() === input.value // edited

Hope this helps someone.