I am trying to wrap only selected text with a specific tag using a javascript tag. I find the code, but when I click the button, it adds a tag that I do not need, because I want to apply the tag only to the selected element.
Example JS code:
function wrapText(elementID, openTag, closeTag) {
var textArea = $('#' + elementID);
var len = textArea.val().length;
var start = textArea[0].selectionStart;
var end = textArea[0].selectionEnd;
var selectedText = textArea.val().substring(start, end);
var replacement = openTag + selectedText + closeTag;
textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
}
$('#bold').click(function() {
wrapText("myTa", "<strong>", "</strong>");
});
$('#italic').click(function() {
wrapText("myTa", "<em>", "</em>");
});
$('#underline').click(function() {
wrapText("myTa", "<u>", "</u>");
});
$('#code').click(function() {
wrapText("myTa", "<pre><code>", "</code></pre>");
});
This is the full working code Link
Any help would be appreciated.
user3931708
source
share