I have read a number of questions similar to this. And some of the solutions work. However the only way I can get this to work is to allow the character to be typed, and then remove it. It looks messy and feels hacky.
How do I prevent the character from being typed in the first place?
Demo: https://jsfiddle.net/jf8bqp5z/
HTML:
<input type="text" name="test" id="test"/>
jQuery:
$('#test').keyup(function(e){
var $this = $(this);
var val = $this.val();
if( val.indexOf('.') ){
val = parseInt(val);
$this.val(val);
e.preventDefault();
}
});
SOLUTION
Actually really simple. I've switched the keyup
event for keydown
and just look for the keyCode:
$('#test').keydown(function(e){
var $this = $(this);
var val = $this.val();
if( e.keyCode === 65 ){ //Here provide the JavaScript event keycode of the key to prevent being typed.
e.preventDefault();
}
});
Demo : https://jsfiddle.net/j80hryvm/
Note : You can get the keycode from http://keycode.info/