How do I capture the input value on a paste event?

后端 未结 5 1054
清歌不尽
清歌不尽 2020-12-05 10:08

On my site users can paste text (in this case a url) into an input field. I\'d like to capture the value of the text that was pasted using jQuery. I\'ve got this to work in

相关标签:
5条回答
  • 2020-12-05 10:59

    Listen for the change event as well as paste. change will reliably fire on a changed field before submission, whereas paste only happens on browsers that support it on an explicit paste; it won't be triggered by other editing actions such as drag-and-drop, cut-copy, undo-redo, spellcheck, IME substitution etc.

    The problem with change is that it doesn't fire straight away, only when editing in a field is finished. If you want to catch all changes as they happen, the event would be input... except that this is a new HTML5 feature that isn't supported everywhere (notably: IE<9). You could nearly do it by catching all these events:

    $('.url').bind('input change paste keyup mouseup',function(e){
        ...
    });
    

    But if you want to definitely catch every change quickly on browsers that don't support input, you have no choice but to poll the value on a setInterval.

    0 讨论(0)
  • 2020-12-05 11:04

    jQuery has a problem with the live-method with the paste-event in the IE; workaround:

    $(document).ready(function() {
        $(".url").bind('paste', function(event) {
            var _this = this;
            // Short pause to wait for paste to complete
            setTimeout( function() {
                var text = $(_this).val();
                $(".display").html(text);
            }, 100);
        });
    });
    

    Fiddle: http://jsfiddle.net/Trg9F/

    0 讨论(0)
  • 2020-12-05 11:05
    $('input').on('paste', function(e) {
        // common browser -> e.originalEvent.clipboardData
        // uncommon browser -> window.clipboardData
        var clipboardData = e.clipboardData || e.originalEvent.clipboardData || window.clipboardData;
        var pastedData = clipboardData.getData('text');
    });
    
    0 讨论(0)
  • 2020-12-05 11:10

    Even better is it to use e.originalEvent.clipboardData.getData('text'); to retrieve pasted data;

    $("input").on("paste", function(e) { 
        var pastedData = e.originalEvent.clipboardData.getData('text');
        // ... now do with pastedData whatever you like ...
    });
    

    This way you can avoid timeouts and it is supported on all major browsers.

    0 讨论(0)
  • 2020-12-05 11:13

    Maybe try using the onblur event instead. So the user c/p into the input and when they leave the field the script checks what's there. This could save a whole lot of hassle, since it works for mouse and key c/p as well as manually entered input.

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