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?
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:
As @pimvdb notes, you will need to use "
e.originalEvent.clipboardData
" if using jQuery.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.
I needed to implement a "trim" on whatever was pasted (remove all leading and trailing whitespace) while still allowing the use of the spacebar.
For Ctrl+V, Shift+Insert and mouse right-click Paste, here is what I found worked in FF, IE11 and Chrome as of 2017-04-22:
Two caveats:
If there is already text when the paste occurs, trimming occurs on the entire result, not just what it being pasted.
If the user types space or BS or Del and then pastes, trimming will not occur.