This object will let you get, set & modify the selected region of a text box.
function SelectedText(input) {
// Replace the currently selected text with the given value.
this.replace = function(text) {
var selection = this.get();
var pre = input.value.substring(0, selection.start);
var post = input.value.substring(selection.end, input.value.length);
input.value = pre + text + post;
this.set(selection.start, selection.start + text.length);
return this;
}
// Set the current selection to the given start and end points.
this.set = function(start, end) {
if (input.setSelectionRange) {
// Mozilla
input.focus();
input.setSelectionRange(start, end);
} else if (input.createTextRange) {
// IE
var range = input.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
return this;
}
// Get the currently selected region.
this.get = function() {
var result = new Object();
result.start = 0;
result.end = 0;
result.text = '';
if (input.selectionStart != undefined) {
// Mozilla
result.start = input.selectionStart;
result.end = input.selectionEnd;
} else {
// IE
var bookmark = document.selection.createRange().getBookmark()
var selection = inputBox.createTextRange()
selection.moveToBookmark(bookmark)
var before = inputBox.createTextRange()
before.collapse(true)
before.setEndPoint("EndToStart", selection)
result.start = before.text.length;
result.end = before.text.length + selection.text.length;
}
result.text = input.value.substring(result.start, result.end);
return result;
}
}