I have two input numbers (min and max). Is there a way to prevent user inserting values like min > max?
<input type="number" class="inputMin" placeholder="Min.">
<input type="number" class="inputMax" placeholder="Max.">
I have two input numbers (min and max). Is there a way to prevent user inserting values like min > max?
<input type="number" class="inputMin" placeholder="Min.">
<input type="number" class="inputMax" placeholder="Max.">
There are many different ways you can do this.
One option is whenever min is changed, if it is greater than max, change it to equal max, like this:
$('.inputMin').on('change', function() {
var max = parseFloat($('.inputMax').val());
var min = parseFloat($('.inputMin').val());
if (min > max) {
$('.inputMin').val(max);
}
});
or the opposite case when you change max:
$('.inputMax').on('change', function() {
var max = parseFloat($('.inputMax').val());
var min = parseFloat($('.inputMin').val());
if (min > max) {
$('.inputMin').val(max);
}
});
Another option is to display an error, either when the form is submitted, or dynamically as the user changes the input.
There are a number of javascript libraries that allow you to do dynamic validation very easily. Check out Angular.js, and how to use it for form validation.
parseFloat. Just updated the answer.Without JQuery, you can try this :
(and you have to change class to id)
var min = document.getElementById("inputMin");
var max = document.getElementById("inputMax");
function check() {
if (min.value > max.value) {
min.value = max.value;
}
};
min.addEventListener("input", check, false);
max.addEventListener("input", check, false);
You can try it there
You can use the parameters min and max like:
<form>
Quantity (between 1 and 5):
<input type="number" name="quantity" min="1" max="5">
</form>
Ref: http://www.w3schools.com/html/html_form_input_types.asp (Input Type: number)
Also you can use Javascript to check if the value is >= min_number and <= max_number, but both are client side scripts, which can be bypassen with editing the html part.
You also need a server-side check so you can be sure it's within the range.