views:

298

answers:

2

I want to hook paste event for <input type="text"> and force this text to be pasted into hidden textarea (then I want to parse textarea's text and perform 'paste data from excel to gridview' action). Something like:

$('#input1').bind('paste', function(e) {
    // code do paste text to textarea instead of originally targeted input
});

What cross-browser code should I write instead of comments?

Thanks.

+1  A: 

There is this hacky solution that fires a focus event on a textarea when Ctrl and V keys or Shift and Insert keys are down. [Yes, it doesn't work for contextmenu -> past]

$(document).ready(function(){
    var activeOnPaste = null;
    $('#input1').keydown(function(e){
        var code = e.which || e.keyCode;
        if((e.ctrlKey && code == 86) || (e.shiftKey && code == 45)){
            activeOnPaste = $(this);
            $('#textarea').val('').focus();
        }
    });
    $('#textarea').keyup(function(){
        if(activeOnPaste != null){
            $(activeOnPaste).focus();
            activeOnPaste = null;
        }
    });
});

The code lets the pointer focus on a textarea when Ctrl and V keys are down. At that moment no text is pasted, it's pasted after this keydown function is fired so the pasted text is shown in the textarea. After that, on keyup on that textarea, #input1 will be focused.

While typing this, I see that there may be a solution for both keyboard pasting and mouse pasting, using ranges. I'll try something with that too...

Harmen
Interesting idea, thanks. Hope you will post mouse pasting solution too.
Roman
A: 

You should bind a function to your input-fields onChange() event and copy its content everytime this function is called and process the data afterwards. If you are specifically interested in "pasted" content (I do not know what you are trying to do there, but generally it is a sign of bad concept to be in a situation where pasted content has to be treated additionally) you can try implementing a counter that checks the input speed (eg more than xx characters per second -> PASTE-Eventcall)

ThE_-_BliZZarD