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();
}
});
};
15 thoughts on “jQuery Select Text Range”
Thank for the hint 🙂 JQuery rules!
Val Che
You’re welcome 🙂 Glad you found it useful. jQuery really is nice to work with!
Mark
Hey man, grate thanks to your code!
Jquery is really nice for our coding, and your code make my job much easier.
Pougin
This is a great function. This really should be added to the core. Thanks for sharing it.
Cheddar
The code seems awesome but it would be great a demo that demostrate the usage.
Joshep
Hey Joshep, good point! Here’s a working demo: http://jsfiddle.net/mnbayazit/WpqsN/
Mark
Hi Mark,
Great useful snippet.
Would be even better if you could point out how to “get” a selected text range.
Robin
Hey Robin,
Here’s a quick example I did up to get the selected text: http://jsfiddle.net/mnbayazit/Q5KP5/
Mark
Mark
It was useful for me. Thank you very much!
Tim
Useful function but you should also mention the place you got it from 🙂
Kareem
@Kareem:
Would you be referring to my post on stackoverflow?
Mark
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?
titchagcreation
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!
Mark
O.M.G. Thank you!
David Weis
Re https://stackoverflow.com/questions/59557352/alternative-to-branch-reset-groups-in-javascript
[…new URLSearchParams(str.match(/(x|y)=\d+(?=;|$)/g).join(“&”)).entries()]
{x:void 0, …Object.fromEntries(new URLSearchParams(str.replace(/;/g,”&”)))}
guest271314