views:

61

answers:

2

I want my script to select just a part of the text inside a text field (<input type="text"). How can I do this?

+1  A: 

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
Why do you need jQuery for that?
Tim Down
@Tim You don't.
Josh Stodola
A: 

Check out http://stackoverflow.com/questions/646611/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/

marapet
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