How do I restrict user input to a given length in an HTML5 input[type=number] textbox?
the answers to
How can I limit possible inputs in a HTML
Here is my suggestion after testing a few things
defaultValues of the fields with the classLive Demo
var inputQuantity = [];
$(function() {
$(".quantity").each(function(i) {
inputQuantity[i]=this.defaultValue;
$(this).data("idx",i); // save this field's index to access later
});
$(".quantity").on("keyup", function (e) {
var $field = $(this),
val=this.value,
$thisIndex=parseInt($field.data("idx"),10); // retrieve the index
// NOTE :invalid pseudo selector is not valid in IE8 so MUST be last
if (this.validity && this.validity.badInput || isNaN(val) || $field.is(":invalid") ) {
this.value = inputQuantity[$thisIndex];
return;
}
if (val.length > Number($field.attr("maxlength"))) {
val=val.slice(0, 5);
$field.val(val);
}
inputQuantity[$thisIndex]=val;
});
});