EdwardBlack EdwardBlack - 11 months ago 51
Javascript Question

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

, then the selected text should be wrapped in

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.


enter image description here

Answer Source

Try this:

function getSel() // javascript

    // 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);