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

后端 未结 2 768
再見小時候
再見小時候 2020-12-04 17:26

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

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

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 17:31

    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')
    })
    
    
    

提交回复
热议问题