SantyEssac SantyEssac - 3 months ago 8
jQuery Question

Masking to input type text to only 4 digits

I am trying restrict a user from entering more than 4 digits.

For that I am using:

$("#YEAR").mask("(9999)");


But I'm getting the following error:


JavaScript runtime error: Object doesn't support property or method 'mask'


Do I need to include a library for it?

Answer

A simple solution could be:

$(function () {
  $('#YEAR').on('keypress', function(e) {
    var charCode = (e.which) ? e.which : event.keyCode
    if (charCode < 48 || charCode > 57) {
      return false;
    }
    return true;
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
    <input type="text" maxlength="4" id="YEAR" name="YEAR"/>
</form>