Is it possible to detect how many characters are being pasted into a HTML textarea, and cancel the paste if beyond a limit?
Edit: what I am trying to do is prevent the user pasting a massive amount of characters (~3 million) because it crashes some browsers. So I want to cancel the paste before their browser locks up. I am making a document editor where users are likely to try this. But they can type as much as they want.
This jquery attaches the anonymous function to textareas, this will trim the text and alert the user, you can also attach it to the keypress event.
See: http://viralpatel.net/blogs/2008/12/set-maxlength-of-textarea-input-using-jquery-javascript.html for further details on that.
In IE, you can use the
onPaste
event. (MSDN documentation)In Firefox, Safari, Opera and Chrome you can use the
onInput
event (Dottoro.com reference). This event fires when the text content of the element is changed through the user interface, including pasting.You can't access the clipboard content via JS, so you can't prevent it. However, you have three options:
These are just some suggestions, and if you find another way to do this, please let me know it.
you can do this on jQuery like this:
view a demo here.
I'd use jQuery and add an event handler for the textarea. When the handler fires, do the count and respond as desired.