jquery - How to restrict user input character length of HTML5 input type="number"? -
how restrict user input given length in html5 input[type=number]
textbox?
the answers
how can limit possible inputs in html5 "number" element?
do not handle illegal inputs
<input class="quantity" type="number" min="0" max="99999" maxlength="5" /> $("quantity").keyup(function(){ var $field = $(this); if ($field.val().length > number($field.attr("maxlength"))) { var value = $field.val().slice(0, 5); $field.val(value); } });
i know maxlength attribute not supported, use obtain given length.
the above code works fine in firefox, in chrome , safari works if input 5 "valid" characters. when start typing invalid characters, e.g. "a", "b" etc., able type in more letters , textbox color changes red.
i found when input becomes invalid $field.val()
returns empty string , $field.val().length
returns 0
.
i tried converting keycode character intended input , store in "data-value" attribute input box check against , overwrite value of input didn't seem reliable.
is there solution can make input[type=number]
behave same input[type=text][maxlength=5]
?
here suggestion after testing few things
- it handles more 1 field quantity class
- it handles illegal input supported
- initialises storing
defaultvalue
s of fields class - handles weirdness .index()
- works in ie<10 too
- tested in safari 5.1 on windows - reacted is(":invalid") invalid in ie8
var inputquantity = []; $(function() { $(".quantity").each(function(i) { inputquantity[i]=this.defaultvalue; $(this).data("idx",i); // save field's index access later }); $(".quantity").on("keyup", function (e) { var $field = $(this), val=this.value, $thisindex=parseint($field.data("idx"),10); // retrieve index // note :invalid pseudo selector not valid in ie8 must 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; }); });
Comments
Post a Comment