简体   繁体   中英

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.

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

  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.

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();
                }       
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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