d
Amit DhamuSoftware Engineer
 

Restrict Input to Numbers

2 minute read 00000 views
<input
  type="text"
  name="inputTxt"
  onkeypress="return numbersonly(this, event);"
/>
function numbersonly(myfield, e, dec) {
  var key
  var keychar

  if (window.event) {
    key = window.event.keyCode
  } else if (e) {
    key = e.which
  } else {
    return true
  }
  keychar = String.fromCharCode(key)

  if (
    key == null ||
    key == 0 ||
    key == 8 ||
    key == 9 ||
    key == 13 ||
    key == 27
  ) {
    // control keys
    return true
  } else if ('0123456789.'.indexOf(keychar) > -1) {
    // numbers
    return true
  } else if (dec && keychar == '.') {
    // decimal point jump
    myfield.form.elements[dec].focus()
    return false
  } else {
    return false
  }
}