Here is an example of how your script could look like:
var value, min=6, max=100;
function isNumberPressed(k) {
// 48-57 are number 0-9 on a normal keyboard, 96-105 are keypad numbers
return (k > 47 && k < 58) || (k > 95 && k < 106) ? true : false;
}
function isValidNumber(v){
// Check if a valid number is entered
return (parseInt(v, 10) >= min && parseInt(v, 10) <= max) ? true : false;
}
$(document).ready(function() {
$("#test").keydown(function(e) {
// See if a valid key is pressed
if(isNumberPressed(e.keyCode)){
if(isValidNumber($(this).val())) value = $(this).val();
}
// Do nothing if unallowed keys are pressed
else if(e.keyCode != 46 && e.keyCode != 8) return false;
}).keyup(function(){
// If the value, including the latest number that's added, is not valid (to high or to low), show the old value again
if(isValidNumber($(this).val()) == false){
$(this).val(value);
}
});
});
But it has a big disadvantage, you can't enter 26 if the minimum is 6, because 2 < 6. This is not a problem if you have a minimum less than or equal to 10.
However, if your minimum is more than 10, you could consider this code:
var timer, min=36, max=100;
function isValidNumber(v){
// Check if a valid number is entered
return (parseInt(v, 10) >= min && parseInt(v, 10) <= max) ? true : false;
}
$(document).ready(function() {
$("#test").keydown(function(e) {
that = this;
// Clear the timer
if(timer)
clearTimeout(timer);
// Set a new timer with a delay of one second
timer = setTimeout(function(){
if(isValidNumber($(that).val()) == false) $(that).addClass('error');
else $(that).removeClass('error');
}, 1000);
});
});
It checks the input with a delay of one second. You need some CSS code for this, for example:
input.error {
border: 2px solid red;
}
Both scripts check the values on the fly, which is a great method.