Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I capture the input value on a paste event?

Tags:

On my site users can paste text (in this case a url) into an input field. I'd like to capture the value of the text that was pasted using jQuery. I've got this to work in FF using the code below, but it doesn't work in IE (I don't think IE supports the "paste" event).

Anyone know how to make this work across all modern browsers? I've found a few other answers to this on SO but most are FF-only and none seemed to offer a complete solution.

Here's the code I have so far:

$("input.url").live('paste', function(event) {     var _this = this;     // Short pause to wait for paste to complete     setTimeout( function() {         var text = $(_this).val();         $(".display").html(text);     }, 100); }); 

JSFiddle: http://jsfiddle.net/TZWsB/1/

like image 610
rolling stone Avatar asked Aug 01 '11 18:08

rolling stone


People also ask

How do I paste text into Javascript?

We'll first need to assign this field to a variable and attach a click handler. const paste = document. getElementById('paste'); paste. addEventListener('click', () => { // Do our action });

How do I disable paste in HTML?

You can disable cut, copy, and paste using the oncut, oncopy, and onpaste event attributes with the target HTML elements. If you want to disable cut, copy, and paste for the complete web page, you need to use these event attributes with the body tag.


2 Answers

jQuery has a problem with the live-method with the paste-event in the IE; workaround:

$(document).ready(function() {     $(".url").bind('paste', function(event) {         var _this = this;         // Short pause to wait for paste to complete         setTimeout( function() {             var text = $(_this).val();             $(".display").html(text);         }, 100);     }); }); 

Fiddle: http://jsfiddle.net/Trg9F/

like image 110
scessor Avatar answered Sep 24 '22 07:09

scessor


$('input').on('paste', function(e) {     // common browser -> e.originalEvent.clipboardData     // uncommon browser -> window.clipboardData     var clipboardData = e.clipboardData || e.originalEvent.clipboardData || window.clipboardData;     var pastedData = clipboardData.getData('text'); }); 
like image 41
Sakamoto Riku Avatar answered Sep 21 '22 07:09

Sakamoto Riku