JSFiddle - React, Tailwind, and code Playground
HTML
<form name="my_form">
<textarea id="my_textarea" onselect="getSelectedText()" class="txtarea" ></textarea><br />
<input type="button" value="bold" onclick="formatText('b');" />
<input type="button" value="italic" onclick="formatText('i');" />
<input type="button" value="underline" onclick="formatText('u');" />
</form>
<br/>
CSS
.bold {
font-weight:bold;
}
.italic {
font-style: italic;
}
.underline{
text-decoration: underline;
}
.txtarea{
width: 300px;
height:100px;
}
JavaScript
$(document).ready(function() { });
var txtArea;
var txtAreaTextLength;
var selectedText;
var selectedTextNew;
var startPosition;
var endPosition;
function getSelectedText()
{
this.txtArea = document.getElementById("my_textarea");
this.selectedText;
if (this.txtArea.selectionStart != undefined)
{
this.startPosition = this.txtArea.selectionStart;
this.endPosition = this.txtArea.selectionEnd;
this.selectedText = this.txtArea.value.substring(this.startPosition, this.endPosition);
this.txtAreaTextLength = this.txtArea.value.length;
}
alert("You selected :" + this.selectedText + " : " + this.txtAreaTextLength + " - " + this.txtArea.value.length);
}
function addSpanAndBoldCss(){
this.selectedTextNew = "<span class='bold'>" + this.selectedText + "</span>";
this.txtArea.value.replace(this.selectedText, this.selectedTextNew)
alert(this.txtAreaTextLength);
}
function formatText(tag) {
addSpanAndBoldCss();
$( "#my_textarea" ).select();
}