最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to get pasted text without using the setTimeout() function? - Stack Overflow

programmeradmin4浏览0评论

I found out that when pasting text (i.e. Hello) by using the mouse, the following function will throw an empty popup:

$('input:text').onpaste = function()
{
    alert($('input:text').val());
});

The thing is, when the onpaste event is being fired, the text is not yet actually pasted to the input field (at least that's my guess). So changing the function to:

$('input:text').onpaste = function()
{
    setTimeout(function()
    {
        alert($('input:text').val()
    }, 100);
}

gives a correct result by showing a popup with the text Hello when pasted to the input field.

Now my question: is there is any possibility to catch the pasted text without using the setTimeout() function? This workaround seems quite dirty so I'd love to not have to use it.

kkthxbai xon1c

I found out that when pasting text (i.e. Hello) by using the mouse, the following function will throw an empty popup:

$('input:text').onpaste = function()
{
    alert($('input:text').val());
});

The thing is, when the onpaste event is being fired, the text is not yet actually pasted to the input field (at least that's my guess). So changing the function to:

$('input:text').onpaste = function()
{
    setTimeout(function()
    {
        alert($('input:text').val()
    }, 100);
}

gives a correct result by showing a popup with the text Hello when pasted to the input field.

Now my question: is there is any possibility to catch the pasted text without using the setTimeout() function? This workaround seems quite dirty so I'd love to not have to use it.

kkthxbai xon1c

Share Improve this question asked Jun 18, 2011 at 19:11 xon1cxon1c 4235 silver badges12 bronze badges 1
  • stackoverflow./a/19269040/530153 – Rajat Gupta Commented Jan 31, 2015 at 6:05
Add a ment  | 

4 Answers 4

Reset to default 12

you can use the oninput event instead, modern browsers support this method

http://jsfiddle/pxfunc/KDLjf/

$('input').bind('input', function(e) {
    console.log($(this).val());
}); 
$('input:text').bind('paste', function() { 
    alert($(this).val());
});

try this to get the data being pasted:

$("input:text").bind('paste', function(e) {
     var text = e.event;
     alert(text);
});

The timeout is needed to get the dom updated so the value is actually in the input field. you could also use the change event to check if the input box is updated http://api.jquery./change

I don't think the bellow code works on IE8 since the input value is not changed when alert() executed.

 $('input').bind('input paste', function(e) {
     alert($(this).val());
 }); 

on Firefox and Chrome, it works fine.

发布评论

评论列表(0)

  1. 暂无评论