I have an HTML form in which I need to allow only numeric key-press. For this i have used the following code
$(".span8").keypress(function(e)
{
var unicode=e.charCode? e.charCode : e.keyCode
//alert(unicode);
if ((unicode ==8) || (unicode==9)|| (unicode==46)){
//if the key isn't the backspace key (which we should allow)
}
else
{
if (unicode<48||unicode>57&&unicode!=65) //if not a number
return false //disable key press
}
});
but here if I am testing keycode, I am getting value as 46 for delete key. 46 is for dot(- period) Others values are ing correct. I am not able to find were am I going wrong. Please help
I have an HTML form in which I need to allow only numeric key-press. For this i have used the following code
$(".span8").keypress(function(e)
{
var unicode=e.charCode? e.charCode : e.keyCode
//alert(unicode);
if ((unicode ==8) || (unicode==9)|| (unicode==46)){
//if the key isn't the backspace key (which we should allow)
}
else
{
if (unicode<48||unicode>57&&unicode!=65) //if not a number
return false //disable key press
}
});
but here if I am testing keycode, I am getting value as 46 for delete key. 46 is for dot(- period) Others values are ing correct. I am not able to find were am I going wrong. Please help
Share Improve this question edited Jun 27, 2014 at 10:15 Sr.Richie 5,7405 gold badges40 silver badges62 bronze badges asked Jun 27, 2014 at 8:45 shikhathakurshikhathakur 152 silver badges7 bronze badges 3- 2 check this : cambiaresearch./articles/15/javascript-char-codes-key-codes – Amit Commented Jun 27, 2014 at 8:52
- javascriptkit./javatutors/javascriptkey2.shtml – Sasi Commented Jun 27, 2014 at 8:59
- thanks @Sasi. The code helped me!!! – shikhathakur Commented Jun 27, 2014 at 9:15
1 Answer
Reset to default 5I've found this weird behaviour too with the keypress
function.
Instead, try the following:
jQuery(function($) {
var input = $('.span8');
input.on('keydown', function() {
var key = event.keyCode || event.charCode;
if(key == 8 || key == 46)
//Do something when DEL or Backspace is pressed
});
});