I simply try to replace the selected text from an input field e.g from a textarea, with another text.
E.g. if i select a part of the text inside the input field and click the Button CENTER
, then the selected text should be wrapped in <center></center>
.
I found this "solution" from 2009 which seems to be outdated, I tried it with Chrome and Firefox and I get the info that my browser is not supported.
Is there another way to achieve this? It should work at least with Firefox and Chrome.
Try this:
function getSel() // javascript
{
console.log("test");
// obtain the object reference for the textarea>
var txtarea = document.getElementById("mytextarea");
// obtain the index of the first selected character
var start = txtarea.selectionStart;
// obtain the index of the last selected character
var finish = txtarea.selectionEnd;
//obtain all Text
var allText = txtarea.value;
// obtain the selected text
var sel = allText.substring(start, finish);
//append te text;
var newText=allText.substring(0, start)+"<center>"+sel+"</center>"+allText.substring(finish, allText.length);
console.log(newText);
txtarea.value=newText;
}
https://jsfiddle.net/qpw1eemr/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With