webcloud

Selecting text with JavaScript

When dealing with JavaScript text selection you will encounter some differences between browser implementations.

Selecting all text in an input is easily enough with the select method

document.getElementById("target-input-or-textfield").select()

The real trouble starts when we need to select a specified range of text.

Textrange

Using object detection rather than browser sniffing we can ensure cross-browser compatibility.

function createSelection(start, end, field) {

    if ( field.createTextRange ) {

        /* 
        IE calculates the end of selection range based 
        from the starting point.
        Other browsers will calculate end of selection from
        the beginning of given text node.
        */

        var newend = end - start;
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart("character", start);
        selRange.moveEnd("character", newend);
        selRange.select();
    } 

    /* For the other browsers */

    else if( field.setSelectionRange ){

        field.setSelectionRange(start, end);
    } 

    field.focus();
}

/* 
Usage 
*/

var target = document.getElementById("target-input-or-textfield");
createSelection(10, 20, target);

As you can see, like many times before, IE requires it's own treatment.

Demo

Click the button below to select a text range between 5 to 10 in the input field.

Reference