Allow only numeric input in textbox using jQuery

Allow only numeric input in textbox using jQuery

by Leandro Barbosa

HTML

<p>
  <label>Currency</label>
  <input type="text" class="currency">
  <br>
  <span>Numeric values with decimal point and commas</span>
</p>

<p>
  <label>Percentage</label>
  <input type="text" class="percentage">
  <br>
  <span>Numeric values with decimal point</span>
</p>

<p>
  <label>Age</label>
  <input type="text" class="age">
  <br>
  <span>Numeric values only</span>
</p>

CSS

p {
  border: 1px gray solid;
  margin: 0 0 20px 0;
  padding: 10px;
}

JavaScript

//hack: digits only on currency, age and percentage input fields on mobile devices
$('.currency, .age, .percentage').each(function() {
  $(this).attr({
    'type': 'tel',
    'pattern': '[0-9]*',
    'novalidate': true
  });
});

//allow digits only, commas, decimals
$(document).on('keydown', '.currency', function(e) {
  var key = e.key;
  var isTab = key === "Tab" || (key === "Tab" && e.shiftKey);
  var isReload = (key === "r" || key === "F5") && e.ctrlKey;
  if (isTab || isReload) {
    return true;
  }
  var keys = ["Del", "Delete", "Backspace", "Home", "End", "Left", "Right", "ArrowLeft", "ArrowRight", ",", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
  var invalidKey = $.inArray(key, keys) === -1;
  if (invalidKey) {
    e.preventDefault();
  }
});

//allow digits only, decimals
$(document).on('keydown', '.percentage', function(e) {
  var key = e.key;
  var isTab = key === "Tab" || (key === "Tab" && e.shiftKey);
  var isReload = (key === "r" || key === "F5") && e.ctrlKey;
  if (isTab || isReload) {
    return true;
  }
  var keys = ["Del", "Delete", "Backspace", "Home", "End", "Left", "Right", "ArrowLeft", "ArrowRight", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
  var invalidKey = $.inArray(key, keys) === -1;
  if (invalidKey) {
    e.preventDefault();
  }
});

//allow digits only
$(document).on('keydown', '.age', function(e) {
  var key = e.key;
  var isTab = key === "Tab" || (key === "Tab" && e.shiftKey);
  var isReload = (key === "r" || key === "F5") && e.ctrlKey;
  if (isTab || isReload) {
    return true;
  }
  var keys = ["Del", "Delete", "Backspace", "Home", "End", "Left", "Right", "ArrowLeft", "ArrowRight", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
  var invalidKey = $.inArray(key, keys) === -1;
  if (invalidKey) {
    e.preventDefault();
  }
});