textbox max min
Allows only certain numbers to be typed into text boxes of class maxmin. Attributes max, min, and intOnly = "true/false" are set in the tag. Works best with min = 0 or min = 1. If you set min to 5, you won't be able to type in 23 because after you type in the 2, the result will be less than 5 and not be allowed. Works by recording value before key is pressed and if value fails test after key is pressed then it restores the saved value.
by Storm Dog
HTML
<p>
<input type="text" class="maxmin" min="0" max="365" intOnly="true" />
(0-365, integers)</p>
<p>
<input type="text" class="maxmin" min="1" max="10" />
(1.0 - 10.0)</p>
<p>
<input type="text" class="maxmin" min="3" max="100" intOnly="true" />
(3-100, integers) - Not a good use, can't enter 23.</p>
CSS
body {
padding:1em;
}
input {
width:5em;
text-align:center;
}
p {
margin:1em 0;
}
JavaScript
// Run this on document ready to allow only numbers between
// max and min to be entered into textboxes with class="maxmin".
// Attributes max, min, and intOnly="true/false" are set in the tag.
// Min should probably be "0" or "1", or max and min could be single digits.
// Otherwise for example, if min=5, you couldn't enter 23 because 2 < 5.
$(".maxmin").each(function () {
var thisJ = $(this);
var max = thisJ.attr("max") * 1;
var min = thisJ.attr("min") * 1;
var intOnly = String(thisJ.attr("intOnly")).toLowerCase() == "true";
var test = function (str) {
return str == "" || /* (!intOnly && str == ".") || */
($.isNumeric(str) && str * 1 <= max && str * 1 >= min &&
(!intOnly || str.indexOf(".") == -1) && str.match(/^0\d/) == null);
// commented out code would allow entries like ".7"
};
thisJ.keydown(function () {
var str = thisJ.val();
if (test(str)) thisJ.data("dwnval", str);
});
thisJ.keyup(function () {
var str = thisJ.val();
if (!test(str)) thisJ.val(thisJ.data("dwnval"));
})
});