Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 470
xon1c Avatar asked Jun 18 '11 19:06

xon1c


2 Answers

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());
}); 
like image 92
MikeM Avatar answered Nov 12 '22 16:11

MikeM


$('input:text').bind('paste', function() { 
    alert($(this).val());
});
like image 40
Noxt Avatar answered Nov 12 '22 16:11

Noxt