Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept paste event in Javascript

Is there a way to intercept the paste event in JavaScript and get the raw value, change it, and set the associated DOM element's value to be the modified value?

For instance, I have a user trying to copy and paste a string with spaces in it and the string's length exceeds the max length of my text box. I want to intercept the text, remove the spaces, and then set the text box's value with the change value.

Is this possible?

like image 831
Brandon Avatar asked May 17 '11 17:05

Brandon


People also ask

How to capture paste event JavaScript?

Press CTRL + V. Select "Paste" from the Edit menu in your browser. Right click to display the context menu and select the "Paste" command.

How do I paste text into Javascript?

const paste = document. getElementById('paste'); paste. addEventListener('click', () => { // Do our action });

How do I disable paste in HTML?

The onpaste attribute lets us prevent pasting into the form. Adding the autocomplete attribute as well as preventing drag and drop into the element. If you want to avoid the on{event} code in the HTML, you can do it the cleaner way: myElement.


2 Answers

You can intercept the paste event by attaching an "onpaste" handler and get the pasted text by using "window.clipboardData.getData('Text')" in IE or "event.clipboardData.getData('text/plain')" in other browsers.

For example:

var myElement = document.getElementById('pasteElement'); myElement.onpaste = function(e) {   var pastedText = undefined;   if (window.clipboardData && window.clipboardData.getData) { // IE     pastedText = window.clipboardData.getData('Text');   } else if (e.clipboardData && e.clipboardData.getData) {     pastedText = e.clipboardData.getData('text/plain');   }   alert(pastedText); // Process and handle text...   return false; // Prevent the default handler from running. }; 

As @pimvdb notes, you will need to use "e.originalEvent.clipboardData" if using jQuery.

like image 175
maerics Avatar answered Oct 17 '22 19:10

maerics


As it happens, I answered a similar question earlier today. In short, you need a hack to redirect the caret to an off-screen textarea when the paste event fires.

like image 42
Tim Down Avatar answered Oct 17 '22 20:10

Tim Down