views:

1389

answers:

2

How can I programmatically select a specific range of text in an HTML input field? (I don't want to select the entire field, just a subset)

Also, how can I determine the currently selected range in a field?

+7  A: 

Here's how to select a portion of a text box (range select) and get the selected text:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript">
    window.onload = function() {
        var message = document.getElementById('message');
        // Select a portion of text
        createSelection(message, 0, 5);

        // get the selected portion of text
        var selectedText = message.value.substring(message.selectionStart, message.selectionEnd);
        alert(selectedText);
    };

    function createSelection(field, start, end) {
        if( field.createTextRange ) {
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart('character', start);
            selRange.moveEnd('character', end);
            selRange.select();
        } else if( field.setSelectionRange ) {
            field.setSelectionRange(start, end);
        } else if( field.selectionStart ) {
            field.selectionStart = start;
            field.selectionEnd = end;
        }
        field.focus();
    }       
    </script>
</head>
<body>
    <input type="text" name="message" id="message" value="Hello World" />
</body>
</html>
Darin Dimitrov
Thanks a LOT for this one!!!
Tommi Forsström
+3  A: 

Small correction. It seems that IE moveEnd() method moves incrementally so selRange.moveEnd('character', end) should be replaced with selRange.moveEnd('character', end-start):

    function createSelection(field, start, end) {
    if( field.createTextRange ) {
        var selRange = field.createTextRange();
        selRange.collapse(true);
        selRange.moveStart('character', start);
        selRange.moveEnd('character', end-start);
        selRange.select();
    } else if( field.setSelectionRange ) {
        field.setSelectionRange(start, end);
    } else if( field.selectionStart ) {
        field.selectionStart = start;
        field.selectionEnd = end;
    }
    field.focus();
}