0

I am trying to only allow 9 digits in a single field without using JQuery. I am unable to modify html input. Thought this would be simple without JQuery but it doesn't seem that way. Any assistance would be appreciated.

Fiddle: https://jsfiddle.net/wj_fiddle_playground/b46tpaLj/4/

HTML Below:

<input class="formInput" type="text" style="width: 200px;" name="myNumber" id="myNumber" value="">

Javascript Below

function setInputFilter(textbox, inputFilter) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", 
"drop"].forEach(function(event) {
 textbox.addEventListener(event, function() {
  if (inputFilter(this.value)) {
    this.oldValue = this.value;
    this.oldSelectionStart = this.selectionStart;
    this.oldSelectionEnd = this.selectionEnd;
  } else if (this.hasOwnProperty("oldValue")) {
    this.value = this.oldValue;
    this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
  } else {
    this.value = "";
  }
  });
  });
}


setInputFilter(document.getElementById("myNumber"), function(value) {
  return /^\d{9}/.test(value); });
Angular_Newbie
  • 415
  • 1
  • 9
  • 25
  • input `pattern` attribute? – Jejun Apr 23 '21 at 01:26
  • Set the `maxlength` attribute to 9 and the `pattern` attribute to `/^\d{9}$/`. Also, when you copy code from other posts, be sure to link to the original author. Note the similarity between your code and the accepted answer to [HTML text input allow only numeric input](https://stackoverflow.com/q/469357/215552). You may want to try any of the 78 other answers to that question as well. – Heretic Monkey Apr 23 '21 at 01:29

0 Answers0