I want my script to select just a part of the text inside a text field (<input type="text"
). How can I do this?
Asked
Active
Viewed 2,189 times
3

Pieter
- 31,619
- 76
- 167
- 242
-
To clarify, you want a way to set the current selection by specifying a start and end index? Or by matching a regex? Or by modifying the existing selection in some predetermined fashion? Or what? – warrenm Jun 08 '10 at 16:16
-
1Possible duplicate of http://stackoverflow.com/questions/646611/programmatically-selecting-partial-text-in-an-input-field – marapet Jun 08 '10 at 16:41
2 Answers
2
You will need to use Range, and cross-browser compatibility will probably be an issue.
Quirksmode: Creating a Range object from a Selection object
If jQuery is an option, here is a function you can use (reference)...
$.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();
}
});
};

Josh Stodola
- 81,538
- 47
- 180
- 227
0
Check out Programmatically selecting partial text in an input field (may be a duplicate...)
Also, a helpful implementation concerning selected text and cursor position can be found here: http://javascript.nwbox.com/cursor_position/
-
Yup, it seems that my question is a duplicate. It's weird that I never seem to find an existing Stack Overflow question that solves my problem until I post the duplicate. – Pieter Jun 09 '10 at 10:21