I have 2 <input type="number">
: min and max.
It should not be possible to put a value inside max input lower than the value in min input.
In example below you can select the value in max input and type for example 9. This should not be possible.
How can I prevent that?
$(".min-input, .max-input").on("input", function(e) {
var minInput = $(".min-input").val();
var maxInput = $(".max-input").val();
if(maxInput < minInput) {
$(".max-input").val(minInput);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<span class="input-group-text pretext">Min:</span>
<input min="" max="" type="number" class="form-control min-input" name="price_min" value="12">
<br />
<span class="input-group-text pretext">Max:</span>
<input min="" max="" type="number" class="form-control max-input" name="price_max" value="25">
2
Answers
The value of a textbox is a string you have to convert to an number to compare the min/max values, otherwise you’re doing string comparisons and the ‘1’ from the ’12’ is < ‘9’.
The example below uses plain JavaScript and
<input type="range">
so the user can’t type anything out of range. If the value of#min
exceeds the value of#max
#min
value will be clamped to#max
value. If the value of#max
is less than#min
then#max
value is clamped to the value of#min
.Details are commented in the example.