<!-- Modify selected text in a textarea -->
<html>
<head>
<script type="text/javascript">
function ModifySelection () {
var textarea = document.getElementById("myArea");
if ('selectionStart' in textarea) {
// check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
var newText = textarea.value.substring (0, textarea.selectionStart) +
"[start]" + textarea.value.substring(textarea.selectionStart, textarea.selectionEnd) + "[end]" +
textarea.value.substring (textarea.selectionEnd);
textarea.value = newText;
}
}
else { // Internet Explorer before version 9
// create a range from the current selection
var textRange = document.selection.createRange ();
// check whether the selection is within the textarea
var rangeParent = textRange.parentElement ();
if (rangeParent === textarea) {
textRange.text = "[start]" + textRange.text + "[end]";
}
}
}
</script>
</head>
<body>
<textarea id="myArea" cols="56" spellcheck="false" rows="12">Select some text within this field.</textarea>
<button onclick="ModifySelection ()">Modify the current selection</button>
</body>
</html>