Your conditiion was wrong.
You have to test for keycode from 48 to 57. And also for the keypad numbers, which are 96 to 105.
Your original condition explained:
(e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
If the key is not backspace (8)
AND
if the key is not... There is no keycode zero!!
AND
if the key is below keycode 48 OR above keycode 57 --> That's the opposite of what you wish!
Look at the below snippet now ;)
$(".no-numbers").keydown(function(e){
if ( (e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105) ){
swal({
title: "",
text: "Numbers are not allowed"
});
return false;
}
else
{
return true;
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.28.5/sweetalert2.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.28.5/sweetalert2.min.js"></script>
<input class="no-numbers">
Side note... I always tend to test and "prevent" a keyboard press using the keydown
event, which fires first.