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();
}
});
};
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();
}
});
};
March 22nd, 2010 - 06:29
Thank for the hint
JQuery rules!
March 22nd, 2010 - 17:26
You’re welcome
Glad you found it useful. jQuery really is nice to work with!
June 30th, 2010 - 17:40
Hey man, grate thanks to your code!
Jquery is really nice for our coding, and your code make my job much easier.
February 18th, 2011 - 20:59
This is a great function. This really should be added to the core. Thanks for sharing it.
October 15th, 2011 - 20:51
The code seems awesome but it would be great a demo that demostrate the usage.
October 16th, 2011 - 12:26
Hey Joshep, good point! Here’s a working demo: http://jsfiddle.net/mnbayazit/WpqsN/
October 20th, 2011 - 10:25
Hi Mark,
Great useful snippet.
Would be even better if you could point out how to “get” a selected text range.
October 22nd, 2011 - 12:59
Hey Robin,
Here’s a quick example I did up to get the selected text: http://jsfiddle.net/mnbayazit/Q5KP5/
Mark
October 31st, 2011 - 01:37
It was useful for me. Thank you very much!