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开发者_StackOverflow中文版 + v
var value = $(this).val();
alert(value); // returns ""
}
break;
}
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);
});
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.
You need a hack. I've detailed one on Stack Overflow a few times before:
- How can I get the text that is going to be pasted in my html text editor?
- Pasting into contentedittable results in random tag insertion
- JavaScript get clipboard data on paste event (Cross browser)
It's very simple, code below works fine, in my case takes text contained on clipboard.
function onPaste(info) {
var copied = event.view.clipboardData.getData("Text");
alert(copied);
}
In this case variable called copied contains the value that you need.
精彩评论