jQuery Select Text Range

Here’s a jQuery function I wrote which you can use to select a range of text in an input field.

$.fn.selectRange = function(start, end) {
    return this.each(function() {
        if(this.setSelectionRange) {
            this.focus();
            this.setSelectionRange(start, end);
        } else if(this.createTextRange) {
            var range = this.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', start);
            range.select();
        }
    });
};

13 thoughts on “jQuery Select Text Range

  1. You’re welcome :) Glad you found it useful. jQuery really is nice to work with!

  2. Hey man, grate thanks to your code!
    Jquery is really nice for our coding, and your code make my job much easier.

  3. This is a great function. This really should be added to the core. Thanks for sharing it.

  4. The code seems awesome but it would be great a demo that demostrate the usage.

  5. Hi Mark,
    Great useful snippet.
    Would be even better if you could point out how to “get” a selected text range.

  6. Useful function but you should also mention the place you got it from :)

  7. It is not working. I launched the jsfiddle of Mark but it is not working on Firefox. As the date of the post is May 2009 maybe there was any update on the web browser that broke this feature?

  8. You are quite right. It’s stopped working for me in Firefox as well. I will investigate this and get back to you when I’ve found a solution. Thank you for posting!

Leave a Reply

Your email address will not be published. Required fields are marked *