How can I “undo” the programmatic insertion of text into a textarea?

后端 未结 12 685
失恋的感觉
失恋的感觉 2020-12-17 09:27

I have a textarea and a button. Clicking the button causes text to be inserted into the textarea.

Is there a way to allow a user to press Ctrl/Cmd+z to undo the inse

12条回答
  •  青春惊慌失措
    2020-12-17 10:10

    Save the original value of the textarea in its data:

    var $textarea = $('textarea');
    
    $('button').on('click', function () {
        var val = $textarea.val();
    
        $textarea.data('old-val', val).val(val + ' some text');
    });
    

    If you want an array of data (as @ahren suggested), use this:

    var $textarea = $('textarea');
    
    $('button').on('click', function () {
        var val = $textarea.val();
    
        if ( ! $textarea.data('old-val')) {
            $textarea.data('old-val', []);
        }
    
        $textarea.data('old-val').push(val);
    
        $textarea.val(val + ' some text');
    });
    

提交回复
热议问题