Ive built a little bit of code which adds text to a text area box depending on which button is pressed a very simple editor if you like.
Currently the code just inserts the selected text where the cursor is, but if text is highlighted then I would like it to wrap that text as well.
I have a jsfiddle at http://jsfiddle.net/gffeab94/3/
but for clarity the the function is
jQuery("document").ready(function($){
$('#bold').on('click', function () {
_insertAtCaret($('#transcription-page-wikitext'), "'''bold text here'''");
});
$('#italic').on('click', function () {
_insertAtCaret($('#transcription-page-wikitext'), "<del> </del>");
});
$('#strike').on('click', function () {
_insertAtCaret($('#transcription-page-wikitext'), "{{Paul}}");
});
function _insertAtCaret(element, text) {
var caretPos = element[0].selectionStart,
currentValue = element.val();
element.val(currentValue.substring(0, caretPos) + text + currentValue.substring(caretPos));
return false;
}
})
and the html is
<div>
<!-- editor buttons -->
<p>
<button id ="bold" class="btn btn-small btn-info" type="button">Bold</button>
<button id ="italic" class="btn btn-small btn-info" type="button">Italic</button>
<button id ="strike" class="btn btn-small btn-info" type="button">Strikeout</button>
</p>
<!-- text area -->
<textarea name="transcription-page-wikitext" id="transcription-page-wikitext" cols="76" rows="16">some text</textarea>
</div>
How can I change the function to ideally wrap or replace highlighted text, rather than just inserting at the cursor position?