Creating a 4 digit input field using javascript
In this tutorial we’ll make a 4 digit html input. We’ll use a standard input with a ‘postcode’ class:
<input type="text" class="postcode" />
In the end of the document, or in a
$(document).ready(function(){});
block we’ll bind a function to the keydown event for each element:
$('.postcode').each(function(){
$(this).bind('keydown',function(e){
//... code goes here
});
});
Now we’ll get the event code and we’will filter it:
var codelen = 4;
var code = (e.keyCode ? e.keyCode : e.which);
if(
!((code >= 48 && code <= 57 && $(this).val().length < codelen)
|| (code >= 96 && code <= 105 && $(this).val().length < codelen)
|| code == 8 || code == 116 || code == 46
|| (code >= 35 && code <= 40)
)
)
{
e.preventDefault();
}
With this filter we allow any button from 0 to 9 including those in the num pad if the characters in this input are less then codelen.
We also allow the buttons backspace, delete and F5 (8,116,46).
We also allow all the arrows + Home and End buttons.
Every other event is prevented. The full code is:
$('.postcode').each(function(){
$(this).bind('keydown',function(e){
var codelen = 4;
var code = (e.keyCode ? e.keyCode : e.which);
if(
!((code >= 48 && code <= 57 && $(this).val().length < codelen)//0-9
|| (code >= 96 && code <= 105 && $(this).val().length < codelen)//0-9
|| code == 8 || code == 116 || code == 46//bs del f5
|| (code >= 35 && code <= 40)//arrows, home, end
)
)
{
e.preventDefault();
}
});
});