Capture text pasted into a textarea with JQuery

左心房为你撑大大i 提交于 2019-12-30 04:02:27

问题


I have to take the paste event of a text area using JQuery. I have tried the following code but it is not working...

$(document).ready(function()
{ 
  $('#txtcomplaint').keyup(function()
  {  
     TextCounter('txtcomplaint','counterComplaint', 1000 ); 
  }) 
  $('#txtcomplaint').onpaste(function()
  {  
     alert()
     //TextCounter('txtcomplaint','counterComplaint', 1000 ); 
  }) 
});

回答1:


You can do something like this

$("#txtcomplaint").bind('paste', function(e) {
    var elem = $(this);

    setTimeout(function() {
        // gets the copied text after a specified time (100 milliseconds)
        var text = elem.val(); 
    }, 100);
});



回答2:


$('#txtcomplaint').bind('paste', function(e){ alert('pasting!') });

For additional resource take a look here.




回答3:


I finally got this to work for 1) typing, 2) drag and drop, 3) Ctrl-V and 4) paste from the context menu of a mouse click, but I had to attach the paste and drop handlers to the document (where 'taValue' is the class of the textareas I'm trying to monitor):

        $(document).on("paste drop", '.taValue', function (e) {
          myHandler.call(e.target, e);
        });

The keyup event on the textarea already worked. The next problem was that the paste and drop events get fired BEFORE the text in the textarea actually changes. In my case I wanted to compare the new text to the original text. I resorted to a setTimeout:

    function myHandler(e) {
      if (e && (e.type === "drop" || e.type === "paste")) {
        var me = this;
        setTimeout(function () { myHandler.call(me) }, 200);
      }... [more code to do the comparison]

I hate using timeouts for things like this but it does work (when I tried a 100ms interval, it did not).




回答4:


This is the most useful solution:

$("#item_name").bind("input change", function() {});

maybe change is not essential.



来源:https://stackoverflow.com/questions/2242442/capture-text-pasted-into-a-textarea-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!