Abhinandan Abhinandan - 5 months ago 11
jQuery Question

prevent user from entring 0 as a input

I am trying to prevent user from entering 0 in the input box.

HTML code :

<input class="billMenuQuantity" type="number" name="quantity">


Jquery code:

$('.billMenuQuantity').on('keyup keydown', function (e) {
if ($(this).val() < 1 && e.keyCode != 46 && e.keyCode != 8) {
e.preventDefault();
$(this).val(1);
}
});


It's preventing the user from entering the 0 but it's also preventing the user from entering the any other single digit number(i.e 2-9) other than 1.It is accepting the double digit number(i.e 11, 12 etc).

Can any one help me with this?

Answer

Just test code === 96 and length of the input-value

$('.billMenuQuantity').on('keyup keydown', function(e) {
  var code = e.keyCode || e.which;
  if (this.value.length === 0 && code === 96) {
    e.preventDefault();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input class="billMenuQuantity" type="number" name="quantity">

Comments