0

Can someone help me limit input in type="number", because I know that max length is no working in number type and also max can only work in spinner, I want to know how can I limit input while typing it.

<input type="Number" name="id" class="form-control" max="9999999" required>
  • Possible duplicate of https://stackoverflow.com/questions/18510845/maxlength-ignored-for-input-type-number-in-chrome – Hassan Siddiqui Apr 10 '19 at 04:16
  • @HassanSiddiqui it is not a duplicate of that question. That question requests why it isn't working, and the answer works for him. However the OP in this question knows that it wont work, and wants a way to prevent them from going over the max **while** typing. In the answer provided on the first question, it would only notify you that you went over the max when you tried to submit the form. – Aniket G Apr 10 '19 at 14:23

2 Answers2

1

You can add attribute oninput with some JS:

<input type="number" maxlength="6"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"/>

Codepen

villainmeng
  • 126
  • 2
0

You would have to use some javascript. The code is below.

The code basically stores the value of the input (if the length is less than 7), and when the length becomes more than 7, it simply replaces the value of the input field with the stored value.

var text;
document.getElementById("input").addEventListener("keypress", function() {
  if (document.getElementById("input").value.length > 7) {
    document.getElementById("input").value = text;
  }
  else {
    text = document.getElementById("input").value;
  }
});
<form>
  <input type="Number" name="id" class="form-control" id="input" max="9999999" required>
  <input type="submit" value="Submit" />
</form>
Aniket G
  • 3,471
  • 1
  • 13
  • 39