This code below is now working. Credit to Matt-SL who pointed out the difference between substr and substring
This function serve to add tags to the text in a textarea
just like the one you use to put your text in bold in your question&answer on Stackoverflow.
var lastFocus;
$("#bold").click(function (e) {
e.preventDefault();
e.stopPropagation();
befString = "<b>";
aftString = "</b>";
dif = aftString.length - befString.length;
if (lastFocus) {
setTimeout(function () { lastFocus.focus() }, 10);
var textEdit = document.getElementById('textEdit');
var befSel = textEdit.value.substr(0, textEdit.selectionStart);
var aftSel = textEdit.value.substr(textEdit.selectionEnd, textEdit.length);
var select = textEdit.value.substr(textEdit.selectionStart, textEdit.selectionEnd-aftString.length );
textEdit.value = befSel + befString + select + aftString + aftSel;
}
return (false);
});
$("#textEdit").blur(function() {
lastFocus = this;
});
#textEdit{
width:300px;
height:200px;
}
#bold{
font-size:25px;
cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="editToolBar" class="editToolBar">
Select all 2's and
<span id="bold"></b>click here</b></span>
</div>
<textarea id="textEdit" type="text" name="textEdit" size="" class="editDocInput" data-type="" >111112222233333</textarea>
I can't figure out why the string is not being put back together properly. Try it and see for you self.
11111<b>222223</b>33333
- what are you expecting?