Wrap only selected text with html tag using javascript

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.

+4
source share
1 answer

Use this condition: if(start != end){ ... }

http://jsfiddle.net/sherali/bd4np/119/

function wrapText(elementID, openTag, closeTag) {
    var textArea = $('#' + elementID);
    var len = textArea.val().length;
    var start = textArea[0].selectionStart;
    var end = textArea[0].selectionEnd;
    if (start != end){
       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));
    }
}
0
source

Source: https://habr.com/ru/post/1606068/


All Articles