jQuery Tip: How to find out if the text in a textbox is selected with jQuery

Here, we’re sharing a jQuery tip. This tip will help you to know if the text in a text box is <input type=”text” /> selected or not. The result will be true or false.

 

HTML Code


In HTML code, there is one textbox with id “text_selected“. We are triggering a function on a button and alerting the results.

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

Above jQuery code will tell you whether or not all of the text is selected within a text input. It will work on all major browsers.

Duan Lingxin

Duan Lingxin

Content crafter and chief editor at Scratching Info. Also regular contributor on other major online tech platforms. Security Specialist by day and a writer by night, he does his best to instill his knowledge about tech while delivering inspiring and life changing resources through his writing,

More Posts - Website

Leave a Comment