Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get copied value from ctrl+v key event in javascript

This method detects ctrl + v event but I couldnt find how to get the value of it ?

Thanks in advance,

$(".numeric").keydown(function (event) {
    if (event.shiftKey) {
        event.preventDefault();
    }

    switch (event.keyCode) {

        case 86:
            if (event.ctrlKey) { // detects ctrl + v
                var value = $(this).val();
                alert(value); // returns ""
            }
            break;

    }
like image 322
Barış Velioğlu Avatar asked Dec 16 '22 08:12

Barış Velioğlu


2 Answers

All you have to do it hook into the paste event, let it finish by breaking the callstack and then read the value.

It might seem ugly but it is very crossbrowser friendly and saves you creating a lot of crappy code just to read the actual clipboard.

$(".numeric").bind('paste', function (event) {

  var $this = $(this); //save reference to element for use laster


  setTimeout(function(){ //break the callstack to let the event finish

    alert($this.val()); //read the value of the input field   

  },0); 
});

See it in action here: http://jsfiddle.net/Yqrtb/2/

Update:

Since i just recently had to do something similar, i thought i'd share my final implementation, it goes like this:

$('textarea').on('paste',function(e) {
    //store references for lateer use
    var domTextarea = this,
        txt = domTextarea.value,
        startPos = domTextarea.selectionStart,
        endPos = domTextarea.selectionEnd,
        scrollTop = domTextarea.scrollTop;

    //clear textarea temporarily (user wont notice)
    domTextarea.value = '';

    setTimeout(function () {
        //get pasted value
        var pastedValue = domTextarea.value;

        //do work on pastedValue here, if you need to change/validate it before applying the paste

        //recreate textarea as it would be if we hadn't interupted the paste operation
        domTextarea.value = txt.substring(0, startPos) + pastedValue + txt.substring(endPos, txt.length);
        domTextarea.focus();
        domTextarea.selectionStart = domTextarea.selectionEnd = startPos + pastedValue.length;
        domTextarea.scrollTop = scrollTop;

        //do work on pastedValue here if you simply need to parse its ccontents without modifying it


    }, 0);
});
like image 137
Martin Jespersen Avatar answered Feb 22 '23 22:02

Martin Jespersen


It's very much browser dependent. The data is in the event passed to your handler. In safari/chrome, we are listening for the paste event on the input and then doing

event.clipboardData.getData('text/plain')

in the callback and it seems to work ok. You should use your favorite debugger and put a breakpoint into your paste event handler, and look at the event that is passed in.

like image 29
hvgotcodes Avatar answered Feb 23 '23 00:02

hvgotcodes