In my project i have text field that only take numeric value.but when I copy an alphabets using ctl+c and paste using ctl+v it will allow the alphabets in the text field.So
The solution provided by jaychapani almost works for this user's specific question. However, it prevents pasting of anything, even numbers.
I slightly modified the code, and now the Javascript (a) allows users to paste numbers but (b) disallows alphabetical and special characters. I removed the following from jaychapani's example above:
$(".numericOnly").bind("paste",function(e) {
e.preventDefault();
});
The final code would be:
$(function(){
$(".numericOnly").bind('keypress',function(e){
if(e.keyCode == '9' || e.keyCode == '16'){
return;
}
var code;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
if(e.which == 46)
return false;
if (code == 8 || code == 46)
return true;
if (code < 48 || code > 57)
return false;
}
);
$(".numericOnly").bind('mouseenter',function(e){
var val = $(this).val();
if (val!='0'){
val=val.replace(/[^0-9]+/g, "")
$(this).val(val);
}
});
});
This works and will reject alphabetical and special characters when pasted either using Ctl+v or from a menu. I've noticed, however, that sometimes there is sometime latency after the user pastes undesired characters before the form reject them.
Usually, rejection of undesired characters happens just a second or two later. But there was a handful of instances where the wait was about 10 seconds before the text was cleared. I'm guessing this is either because (a) I was refreshing to observe behavior and some strange caching behavior was causing the latency for the Javascript to work quickly or (b) some looping issue with the Javascript or (c) some combo of the both.
This'll work OK in most production environments though. I doubt users are refreshing a page over and over before submitting.
However, I wonder if there's a more optimal solution. Suggestions on improving this would be welcomed.