Halo my friends
Halo my friends

Reputation: 3

How can i limit input in type="number" HTML

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>

Upvotes: 0

Views: 202

Answers (2)

villainmeng
villainmeng

Reputation: 126

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

Upvotes: 1

Aniket G
Aniket G

Reputation: 3512

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>

Upvotes: 0

Related Questions