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

后端 未结 2 764
再見小時候
再見小時候 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')
    })
    <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>

    0 讨论(0)
  • 2020-12-04 17:31

    I found this:

    function wrapText(elementID, openTag, closeTag) {
        var textArea = $('#' + elementID);
        var len = textArea.val().length;
        var start = textArea[0].selectionStart;
        var end = textArea[0].selectionEnd;
        var selectedText = textArea.val().substring(start, end);
        var replacement = openTag + selectedText + closeTag;
        textArea.val(textArea.val().substring(0, start) + replacement + textArea.val().substring(end, len));
    }
    
    $('button').on('click', function() {
      wrapText('test', '<b>', '</b>');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <textarea id="test">This is a test</textarea>
    <button>Surround with &lt;b&gt; tag</button>

    But personaly its not working with content-editable divs.

    0 讨论(0)
提交回复
热议问题