I'm trying to allow users to do simple formatting of text in a textarea used in a comment system (a poor man's text editor). I wWould like to allow them to select text with the cursor and then click on a button to format it. How do I get the JavaScript to grab and return the selected text?
Imagine it should be something like:
<script>
function formatText(field) {
// Gets text
var text;
text = field.value.substring(field.selectionStart, field.selectionEnd);
// Formats it
var text = '<b'> + text + '</b>';
// Returns it
field.value.substring(field.selectionStart, field.selectionEnd); = text;
}
</script>
<body>
<textarea id="field"></textarea><button onclick="formatText('field')">Make bold</button>
</body>
The following code gets selected text, formats it and then sends it back to the textarea—however, it replaces all text in the textarea... So I just need way to replace the selected text in the textarea—rather than all--and I'll be done:
<head>
<script type="text/javascript">
function GetSelection () {
var selection = "";
var textarea = document.getElementById("field");
if ('selectionStart' in textarea) {
// Check whether some text is selected in the textarea
if (textarea.selectionStart != textarea.selectionEnd) {
selection = textarea.value.substring(textarea.selectionStart,
textarea.selectionEnd);
}
}
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) {
selection = textRange.text;
}
}
if (selection == "") {
alert ("No text is selected.");
}
else {
selection = "<b>" + selection + "</b>";
document.getElementById('field').value = selection;
}
}
</script>
</head>
<body>
<textarea id="field" spellcheck="false">Select some text within this field.</textarea>
<button onclick="GetSelection ()">Get the current selection</button>
</body>
I think there is a way to specify document.getElementByID.value.substr which might do it, but I don't know syntax.