Skip to content Skip to sidebar Skip to footer

Partially Select Text Inside Text Field

I want my script to select just a part of the text inside a text field (

Solution 1:

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();
        }
    });
};

Solution 2:

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/


Post a Comment for "Partially Select Text Inside Text Field"