Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace the currently selected text inside an html textarea?

How do I edit the selected text of a textarea form element?

EDIT: as in edit it in-place, replacing the orignal text.

like image 645
Sam Avatar asked Apr 11 '09 20:04

Sam


1 Answers

This works:

function replaceIt(txtarea, newtxt) {
  $(txtarea).val(
        $(txtarea).val().substring(0, txtarea.selectionStart)+
        newtxt+
        $(txtarea).val().substring(txtarea.selectionEnd)
   );  
}
    

$("button").on('click', function() {
  replaceIt($('textarea')[0], 'fun')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>Hello world.</textarea>
<button>Replace with fun</button>
like image 59
cgp Avatar answered Oct 11 '22 15:10

cgp