0

been doing some research, but haven't found a solution for me. Basically, I have a small admin section that requires number inputs for calculations. ONLY numbers. BUT, the user can sometimes COPY AND PASTE including a $ or % character.

Now, I have found this: input field, only numbers jquery/js

$("input[type=text]").keypress(function (e){
  var charCode = (e.which) ? e.which : e.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
});

which works perfectly during TYPING, however, if the user copies and pastes "$1230", it keeps the $ in there. I would like it to auto-strip it....

SO, basically, I am thinking instead of "return false", I need some sort of "replace"? Would that be the best way to go?

Community
  • 1
  • 1
PaulHanak
  • 729
  • 2
  • 9
  • 21

1 Answers1

2

Use on instead of keypress, with events for both keypress and change:

$("input[type=text]").on("keypress change", (function (e){
  var charCode = (e.which) ? e.which : e.keyCode;
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
    return false;
  }
});
Adam Hopkinson
  • 28,281
  • 7
  • 65
  • 99
  • I actually did try that! Well, I tried it with JUST change. :) At any rate, this doesn't seem to work though. Even worse, I can now type anything into the text field and.... it randomly replace the whole thing sometimes.... haha – PaulHanak Aug 06 '12 at 16:15
  • Forgive me, I had a syntax error with the closing parenthesis... It works perfectly except for when I copy and paste the characters in... – PaulHanak Aug 06 '12 at 16:22