Reputation: 4202
I am having a bit of an issue. I am trying to execute my stuff only if the characters entered on the input are NUMBERS.
This is the code at the moment .
$(".jq-sales, .jq-variablecosts, .jq-fixedcosts, .jq-additional-sales, .jq-sales-units, .jq-variablecosts-units, .jq-totalsold-units").keypress(function(event) {
if (event.keyCode >= 48 && event.keyCode <= 57 && event.keyCode >= 96 && event.keyCode <= 105) {
event.preventDefault();
}
else {
// DO my stuff
}
});
What is wrong with my code ?
I want to be able to detect when they are pressed from the num pad and the numbers on top of the keyboard too ..
Upvotes: 0
Views: 75
Reputation: 1022
Your condition is impossible
if (event.keyCode >= 48 && event.keyCode <= 57 && event.keyCode >= 96 && event.keyCode <= 105) {
A number cannot be both between 48 and 57, and also be between 96 and 105
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
Use an or (the || thing)
Also, if you want to do 'your stuff' when the above condition is met, then you should do the stuff when the condition is true, not when its not true.
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {
// do stuff here
} else {
// do nothing
event.preventDefault();
}
Upvotes: 1
Reputation: 875
Your conditional logic will never pass. For example, you're requiring that the keyCode be <= 57 AND >= 96.
Furthermore, once that is resolved, you'd be preventing the number keystrokes and executing your code on the non-numbers.
Thus, you'd want to write the following:
$(".jq-sales, .jq-variablecosts, .jq-fixedcosts, .jq-additional-sales, .jq-sales-units, .jq-variablecosts-units, .jq-totalsold-units").keypress(function(event) {
if (
( event.keyCode >= 48 && event.keyCode <= 57 ) ||
( event.keyCode >= 96 && event.keyCode <= 105 )
)
{
// DO my stuff
}
else {
// Ignore non-numeric input
event.preventDefault();
}
});
Upvotes: 0