Program & Design Tips, tricks, tutorials, and tools on programming & web design

8May/099

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();
        }
    });
};
Tagged as: Leave a comment
Comments (9) Trackbacks (0)
  1. Thank for the hint :-) JQuery rules!

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

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

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

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

  6. Hey Joshep, good point! Here’s a working demo: http://jsfiddle.net/mnbayazit/WpqsN/

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

  8. Hey Robin,

    Here’s a quick example I did up to get the selected text: http://jsfiddle.net/mnbayazit/Q5KP5/

    Mark

  9. It was useful for me. Thank you very much!


Leave a comment

(required)

No trackbacks yet.