简体   繁体   English

仅在jQuery中输入数字

[英]Input numbers only in jquery

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. 我仅在输入中输入的字符为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 .. 我希望能够检测到何时从数字键盘和键盘顶部的数字按下它们。

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 数字不能介于48和57之间,也不能介于96和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();
  }

Your conditional logic will never pass. 您的条件逻辑将永远不会过去。 For example, you're requiring that the keyCode be <= 57 AND >= 96. 例如,您要求keyCode为<= 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();
                }       
            });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM