0

I have written this code, this code is working fine. But I think there should be some better way to write it, instead of just adding keyCode for everything to allow and disallow.

var element = "testField";
var regexNumber = /^\$?(((\d)\,?)+)?((\d)+)(\.(\d)+)?$/;
$("#" + element).keydown(function(event) {

  // Allow only backspace, delete, dot, arrow key, tab, shift+tab
  if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 || (event.keyCode >= 37 && event.keyCode <= 40) || event.keyCode == 9 || event.keyCode == 16) {
    // let it happen, don't do anything                           
  } else {
    // Allow copy, paste, select all only numbers 
    if (((event.keyCode == 65 || event.keyCode == 86 || event.keyCode == 67) && (event.ctrlKey === true || event.metaKey === true))) {
      if (event.originalEvent.clipboardData.getData('Text').match(regexNumber) == null) {
        event.preventDefault();
      }
    }
    // Ensure that it is a number and stop the keypress

    if (event.keyCode < 48 || event.keyCode > 57) {
      event.preventDefault();
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="testField" type="text" />
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Your question is very vague. Please ask ONE question at a time. I duped on paste of chars and floats. I can type ....++++ into your field – mplungjan Apr 03 '20 at 06:14
  • @mplungjan Hey, that question is just about disallowing characters on type or text. My question is that I have a textbox for numeric data. I should allow following things 1. Floating Number 2. Digits with comma 3. Ctrl+A, C, X, V 4. Arrow Keys 5. Backspace 6. Tab/ Shift+Tab 7. Pasting of digits with dot or comma. rest of things should not work. 8.Backspace – Kishan Kumar Gupta Apr 03 '20 at 06:30
  • So first look at the two dupes I posted. Take what you need from them, then ask again if needed – mplungjan Apr 03 '20 at 06:33
  • @mplungjan, I couldn't take care of that case. But you understood my question right? It shouldn't allow anything other than the mentioned thing in comment box. – Kishan Kumar Gupta Apr 03 '20 at 06:34

0 Answers0