jQuery bind to Paste Event, how to get the content of the paste

后端 未结 9 1042
温柔的废话
温柔的废话 2020-11-28 06:08

I have a jquery token tagit plugin and I want to bind to the paste event to add items correctly.

I\'m able to bind to the paste event like so:

    .b         


        
相关标签:
9条回答
  • 2020-11-28 07:10

    It would appear as though this event has some clipboardData property attached to it (it may be nested within the originalEvent property). The clipboardData contains an array of items and each one of those items has a getAsString() function that you can call. This returns the string representation of what is in the item.

    Those items also have a getAsFile() function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry() function).

    For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:

    $(element).bind("paste", function (e) {
        e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
            debugger; 
            // pStringRepresentation now contains the string representation of what was pasted.
            // This does not include HTML or any markup. Essentially jQuery's $(element).text()
            // function result.
        });
    });
    

    You'll want to perform an iteration through the items, keeping a string concatenation result.

    The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.

    0 讨论(0)
  • 2020-11-28 07:14

    This work on all browser to get pasted value. And also to creating common method for all text box.

    $("#textareaid").bind("paste", function(e){       
        var pastedData = e.target.value;
        alert(pastedData);
    } )
    
    0 讨论(0)
  • 2020-11-28 07:14

    On modern browsers it's easy: just use the input event along with the inputType attribute:

    $(document).on('input', 'input, textarea', function(e){
      if (e.originalEvent.inputType == 'insertFromPaste') {
        alert($(this).val());
      }
    });
    

    https://codepen.io/anon/pen/jJOWxg

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