0

As you may see in the snippet I'm able to get the value of the string that is PASTED in the input. I was wondering if there's a simple way to get the value of the CUTED string.

     $('#example').on("paste cut", function(e) {
          var value = '';
          if(e.type == 'paste') {
              value = e.originalEvent.clipboardData.getData('text');
          } else if(e.type == 'cut') {
              // How should I get the removed part of the string
          }
          $('#result').html(value);
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input type="text" id="example" value="Some random value" style="width:80%"></div>
<div id="result"></div>
Samuil Banti
  • 1,735
  • 1
  • 15
  • 26
  • 1
    For security reasons, I don't think most browsers will allow access to the clipboard, this post offers a solution using `setTimeout()` (https://stackoverflow.com/questions/9364617/get-the-value-of-a-textbox-during-cut-event?noredirect=1&lq=1) – Ryan Wilson Aug 01 '18 at 14:45
  • Yes I can get the value of the input if I use setTimeout() but then I need to compare the strings to get the value of the cuted string. I was hoping for a simple solution. – Samuil Banti Aug 01 '18 at 14:52
  • 1
    Just an idea: Would it be an option to set a Listener to "Ctrl + C" and then when it's pressed just save the currently selected text to a variable - boom you know what got copied. https://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text https://stackoverflow.com/questions/17015019/keylistener-in-javascript – Dominik Aug 01 '18 at 14:54

1 Answers1

2

How about this solution using window.getSelection().toString():

     $('#example').on("paste cut", function(e) {
          var value = e.type=='paste'
                    ? e.originalEvent.clipboardData.getData('text')
                    : window.getSelection().toString();
          console.log(e.type+': '+value);
          $('#result').html(value);
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<input type="text" id="example" value="Some random value" style="width:80%"></div>
<div id="result"></div>
Carsten Massmann
  • 26,510
  • 2
  • 22
  • 43