Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace selected text from input fields on button click

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.

Textarea

enter image description here

like image 940
Black Avatar asked Sep 08 '16 11:09

Black


1 Answers

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/

like image 174
Timvr01 Avatar answered Oct 17 '22 01:10

Timvr01