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

  1. it handles more 1 field quantity class
  2. it handles illegal input supported
  3. initialises storing defaultvalues of fields class
  4. handles weirdness .index()
  5. works in ie<10 too
  6. tested in safari 5.1 on windows - reacted is(":invalid") invalid in ie8

live demo

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

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -