Is it possible to get pasted text without using the setTimeout() function?

烂漫一生 提交于 2019-12-18 16:46:09

问题


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


回答1:


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

http://jsfiddle.net/pxfunc/KDLjf/

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



回答2:


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



回答3:


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.com/change




回答4:


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.



来源:https://stackoverflow.com/questions/6398275/is-it-possible-to-get-pasted-text-without-using-the-settimeout-function

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