I have type=number
input field and I have set min
and max
values for it:
Maybe Instead of using the "number" type you could use the "range" type which would restrict the user from entering in numbers because it uses a slide bar and if you wanted to configure it to show the current number just use JavaScript
$(document).on('keyup', 'input[type=number][min],input[type=number][max]', function () {
var _this = $(this);
if (_this.val() === "-")
return;
var val = parseFloat(_this.val());
if (_this.attr("min") !== undefined && _this.attr("min") !== "") {
var min = parseFloat(_this.attr('min'));
if (val < min)
_this.val(min);
}
if (_this.attr("max") !== undefined && _this.attr("max") !== "") {
var max = parseFloat(_this.attr('max'));
if (val > max)
_this.val(max);
}
});
$(document).on('change', 'input[type=number][step]', function () {
var _this = $(this);
var val = parseFloat(_this.val());
if (_this.attr("step") !== undefined && _this.attr("step") !== "") {
var step = parseFloat(_this.attr('step'));
if ((val % step) != 0)
_this.val(val - (val % step));
}
});
$(function () {
$("input").keydown(function () {
// Save old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
;
else
$(this).val($(this).data("old"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" min="0" max="23" value="14" />
With HTML5 max
and min
, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data-
attributes and save the old value:
$(function () {
$("input").keydown(function () {
// Save old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
$(this).data("old", $(this).val());
});
$("input").keyup(function () {
// Check correct, else revert back to old value.
if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))
;
else
$(this).val($(this).data("old"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="number" min="0" max="23" value="14" />
Use this range method instead of number method.
$(function () {
$("#input").change(function () {
// Save old value.
$("#limit").val($("#input").val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="limit" name="limit" value="14" readonly><br>
<input type="range" id="input" name="input" min="0" max="23" value="14"/>
In some cases pattern
can be used instead of min
and max
. It works correctly with required
.