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

Jimbo picture Jimbo · Feb 15, 2011 · Viewed 33.8k times · Source

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

Answer

Tim Down picture Tim Down · Feb 15, 2011

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;
    }
}