3

This is my code

  $(currentClass).keypress(function (e) {

            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
                return false;
            }

  });

The only problem with this is that, every time I hit a key for the first time regardless a letter or a number, it shows up in my content editable span tag. However, the second time I hit a letter key the code works, it only accepts number. I have no idea what is wrong with this code in the first pressing of keys.

PipeMan
  • 141
  • 1
  • 14
  • This is old but wanted to throw this out there, I was running into issues using .keypress and had to switch to something like the solutions below that use the .on syntax. – Joe Ricklefs Nov 21 '19 at 14:45

4 Answers4

1

Use JQuery's .on() method.

$(currentClass).on("keypress",function (e) {

        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }

});

Pradyumna Swain
  • 1,128
  • 1
  • 12
  • 21
1

This is what I used

 if ($.inArray($event.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
        // Allow: Ctrl+A
        ($event.keyCode == 65 && $event.ctrlKey === true) ||
        // Allow: home, end, left, right
        ($event.keyCode >= 35 && $event.keyCode <= 39)) {
        // let it happen, don't do anything
        return;
    }
    // Ensure that it is a number and stop the keypress
    if (($event.shiftKey || ($event.keyCode < 48 || $event.keyCode > 57)) && ($event.keyCode < 96 || $event.keyCode > 105)) {
        $event.preventDefault();
    }

I was able to solve the problem with this. If their suggestion is not working try this.

PipeMan
  • 141
  • 1
  • 14
0

Bind Properly your events

$(document).ready(function(){
   $(body).on("keypress","currentClass",function (e) {
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
            return false;
        }

   });
});
Hoja
  • 1,057
  • 1
  • 12
  • 32
0
$(currentClass).on('keypress', function (e) {
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
               e.preventDefault();
               alert("pressed");
               return false;
    }
});

event - on

This might helps you :)

Yuyutsu
  • 2,509
  • 22
  • 38
  • Hi, it works when I try it on another project, however still its the same as my code when I use it in the project mixed with Angular and Jquery. – PipeMan Jan 07 '15 at 08:58
  • 1
    Example for angular.js : http://plnkr.co/edit/OHWDZo68siDlcrXnLyzJ?p=preview http://stackoverflow.com/questions/17470790/how-to-use-a-keypress-event-in-angularjs – Yuyutsu Jan 07 '15 at 09:03
  • Thanks! I was able to find another solution. This one works, but not with the application that I am doing. – PipeMan Jan 07 '15 at 09:44
  • @PipeMan if you got the answer please share it. :) Thanks!! – Yuyutsu Jan 07 '15 at 09:57
  • Hi! I already posted an answer, please browse the thread. Thanks again! – PipeMan Jan 08 '15 at 00:15