NielsDePils
NielsDePils

Reputation: 251

How to delete a selection of textarea

I'm making a a simple texteditor and for that I'm using a function which gets the selected text of a textarea.

My problem is not getting the selected text but when i add some tags to the selected text, for example bold or italic, it appends. So what I want is to delete the selection first before adding it to the textarea.

Here's my code:

<input type="button" id="bold" value="BOLD"/>
<input type="button" id="undo" value="UNDO"/>
<textarea id="message" cols="50" rows="20"></textarea>

var text = [];
var textarea = document.getElementById('message');
//simple texteditor
function edit(tag) {
    var startPos = textarea.selectionStart;
    var endPos = textarea.selectionEnd;
    var selection = textarea.value.substring(startPos, endPos);
    var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">");
    textarea.value += surrounder;
    updatePreview();
    textarea.focus();
}
document.getElementById('bold').onclick = function () {
    edit('b');
};
document.getElementById('undo').onclick = function () {
    document.execCommand('undo',false,null);
};

thanks in advance!

Upvotes: 0

Views: 1507

Answers (1)

Laurens
Laurens

Reputation: 124

I think this works for you:

var text = [];
var textarea = document.getElementById('message');
//simple texteditor
function edit(tag) {
    var startPos = textarea.selectionStart;
    var endPos = textarea.selectionEnd;
    console.log(startPos);
    var selectionBefore = textarea.value.substring(0, startPos);
    var selection = textarea.value.substring(startPos, endPos);
    var selectionAfter = textarea.value.substring(endPos);
    var surrounder = selection.replace(selection, "<" + tag + ">" + selection + "</" + tag + ">");
    var newText = selectionBefore + surrounder + selectionAfter;
    textarea.value = newText;
    updatePreview();
    textarea.focus();
}
document.getElementById('bold').onclick = function () {
    edit('b');
};
document.getElementById('undo').onclick = function () {
    document.execCommand('undo',false,null);
};

https://jsfiddle.net/3L659v65/

Upvotes: 3

Related Questions