This code snippet shows you how:
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();
}