Recently, I was reluctant to disable insertion into a form element. To do this, I wrote a cross-browser * implementation of the onpaste Internet Explorer (and others) event handler. My solution was to be independent of any third-party JavaScript libraries.
Here is what I came up with. It does not completely disable the insert (for example, the user can insert one character at a time, for example), but he meets my needs and avoids dealing with keyCodes, etc.
// Register onpaste on inputs and textareas in browsers that don't // natively support it. (function () { var onload = window.onload; window.onload = function () { if (typeof onload == "function") { onload.apply(this, arguments); } var fields = []; var inputs = document.getElementsByTagName("input"); var textareas = document.getElementsByTagName("textarea"); for (var i = 0; i < inputs.length; i++) { fields.push(inputs[i]); } for (var i = 0; i < textareas.length; i++) { fields.push(textareas[i]); } for (var i = 0; i < fields.length; i++) { var field = fields[i]; if (typeof field.onpaste != "function" && !!field.getAttribute("onpaste")) { field.onpaste = eval("(function () { " + field.getAttribute("onpaste") + " })"); } if (typeof field.onpaste == "function") { var oninput = field.oninput; field.oninput = function () { if (typeof oninput == "function") { oninput.apply(this, arguments); } if (typeof this.previousValue == "undefined") { this.previousValue = this.value; } var pasted = (Math.abs(this.previousValue.length - this.value.length) > 1 && this.value != ""); if (pasted && !this.onpaste.apply(this, arguments)) { this.value = this.previousValue; } this.previousValue = this.value; }; if (field.addEventListener) { field.addEventListener("input", field.oninput, false); } else if (field.attachEvent) { field.attachEvent("oninput", field.oninput); } } } } })();
To use this to disable insertion:
<input type="text" onpaste="return false;" />
* I know that oninput is not part of the W3C DOM specification, but all the browsers I tested with this code are: Chrome 2, Safari 4, Firefox 3, Opera 10, IE6, IE7, etc. support either oninput or onpaste. Of all these browsers, only Opera does not support onpaste, but it supports oninput.
Note. This will not work on the console or other system using the on-screen keyboard (provided that the on-screen keyboard does not send keys to the browser if each key is selected). If it is possible that your page / application can be used by someone with an on-screen keyboard and Opera (for example, Nintendo Wii, some mobile phones), do not use this script, if you have not checked, the on-screen keyboard sends keys to the browser after each key selection .
Christopher Parker Nov 12 '09 at 17:12 2009-11-12 17:12
source share