Why no one suggested using the OnPaste event? This is fully supported in IE, Safari and Chrome.
Documents for Using OnPaste in IE
Documents for Using OnPaste in Webkit
In jQuery, it will look like this:
$(input).bind("paste", function(e){ RemoveNonAlphaNumeric(); })
This covers 75% of the browser market.
If you use jQuery, OnPaste is automatically normalized in Firefox, so it works there too. If you cannot use jQuery, there is an OnInput event that works.
A working solution is to use the quick setTimeout value, which allows you to populate the input value property.
Mostly like this:
$("input").bind("paste", function(e){RemoveAlphaChars(this, e);}); function RemoveAlphaChars(txt, e) { setTimeout(function() { var initVal = $(txt).val(); outputVal = initVal.replace(/[^0-9]/g,""); if (initVal != outputVal) $(txt).val(outputVal); },1); }
I tested this in IE, Chrome, and Firefox, and it works well. The timeout is so fast, you canβt even see the characters that are deleted.
source share