Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
18
rated 0 times [  22] [ 4]  / answers: 1 / hits: 21911  / 13 Years ago, sat, october 1, 2011, 12:00:00

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;

}

More From » jquery

 Answers
35

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);
});

[#89835] Thursday, September 29, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clarkulisesa

Total Points: 422
Total Questions: 93
Total Answers: 112

Location: Austria
Member since Thu, Jan 7, 2021
3 Years ago
clarkulisesa questions
Mon, Feb 24, 20, 00:00, 4 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;