Js Disabling Backspace Functionality In Firefox
I have following javascript to prevent user from entering invalid characters into a text field. It's working well in chrome but not in firefox. It's preventing the backspace key to
Solution 1:
see http://jsfiddle.net/8ZJZD/1/
var el=document.getElementById('cnfMobileNo');
el.onkeydown=functiononlyNumbers(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if(key===8){return;}
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Just use if(key===8){return;}
Edit:
If you want to exclude more keys, use
var el=document.getElementById('cnfMobileNo');
el.onkeydown=functiononlyNumbers(evt) {
var theEvent = evt || window.event,
key = theEvent.keyCode || theEvent.which,
exclusions=[8,9]; /*Add exceptions here */if(exclusions.indexOf(key)>-1){return;}
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
See it here: http://jsfiddle.net/8ZJZD/2/
You can know the keyCode
of each key using alert(key)
(before key = String.fromCharCode(key)
).
You could also exclude
- The arrow keys: 37,38,39,40
- Enter: 13
- Context menu: 93
- Start and End: 36,35
Solution 2:
Im not sure of the backspace regex but this should work too
$("#myInput").bind('keyup', function(){
val1 = $(this).val();
$(this).val(val1.replace(/[^0-9.]/g,''));
});
You might do away with bind and directly attach keyup
Fiddle - jsfiddle
Post a Comment for "Js Disabling Backspace Functionality In Firefox"