2

I'm attempting to limit an input field to characters only as documented in this SO post. The javascript works great but as noted here and elsewhere it doesn't work when the shift key is pressed. so I can hold the shift key, type 5 and a '%' shows up. So I added this code to simply return on keydown events in which event.shiftKey = true

$(document).on("keydown", ".numbers-only", function (event) {
            if(event.shiftKey){
                return
            }
            numbersOnly(event);
        }); 

This works when I set a breakpoint and step through with the debugger in chrome. However, it does not work in realtime and the numbersOnly(event) function is called even while holding the shift key down.

Why would the function return as it should while debugging, but not in real time?

JHRS
  • 367
  • 4
  • 11

1 Answers1

1

Following code works fine

$(function() {
  $(document).on("keypress", function(event) {
    showChar(event)
  });

  function showChar(e) {
    if (e.shiftKey) {
      return
    }
    console.log(String.fromCharCode(e.charCode) + ": call function numbersOnly(e)");
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <p>Press any character key, with or without holding down the SHIFT key.</p>
</div>
vinayakj
  • 5,591
  • 3
  • 28
  • 48
  • Thanks for the response, I agree that the code should work. I think it must be a chrome/safari thing (two browsers I tried) – JHRS Mar 26 '18 at 01:18