'How to set decimal input range using javascript or html?
I have an input and I need it to be limited to only these values:
Min: 0.01 max 999.99
If I use maxlength="6" I can enter, for instance, 999.99 but also 1000.1 which is not an accepted value.
What I've tried:
1st attempt (not working):
<input type="number" id="quantity" name="quantity" maxlength="6" min="0.01" max="999.99">
2nd attempt (partially working):
let maximumFractionDigits = 2;
const formatNumber = (value) => {
return parseFloat(value.replace(/,/g,'')).toLocaleString('en-US', { maximumFractionDigits });
}
$('input[name="test"]').on('keyup',function(){
maximumFractionDigits = 2;
if (!$(this).val() || (maximumFractionDigits && $(this).val().endsWith('.'))) {
return
}
$(this).val(formatNumber($(this).val()).replace(/,/g,''));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
INPUT TEST
<input type="text" maxlength="6" name="test" class="form-control">
<br>
With the second approach, I still can input weird numbers like 10000. and values like 0.0X can't be introduced (I guess it's rounded), how could I just limit the values to Min: 0.01 max 999.99?
Solution 1:[1]
So basically I found a solution:
const input = document.querySelector('.example');
input.addEventListener('input', updateValue);
function updateValue(e) {
let number = e.target.value;
number = number.toString();
if(number.match(/^\d{1,3}(\.\d{1,2})?$/)){
console.log("True");
} else{
const newNum = (e.target.value).toString().slice(0, -1)
e.target.value = parseFloat(newNum);
}
}
<input type="number" class="form-control example" id="quantity" name="quantity" maxlength="6" min=0.01 max=999.99>
Hope this helps if someone has the same situation
Solution 2:[2]
You can check for 3 conditions, For first 2 convert number to string
The max length of the string should be 6
maxlength = 6If string has decimal point then .split('.') and check the length of decimal numbers
const decimal = input.split('.')[1]Check if the number is
0.01 < number < 999.99
Solution 3:[3]
You have to methods to achieve the same
- change the input type, and set min-max values:
<input type="number" min=0.01 max=999.99 name="test" class="form-control" aria-label="Equipment Procurement %">
- If you don't want to change the type:
const numInput = document.querySelector(".form-control");
numInput.addEventListener("input", (event) => {
const number = parseInt(e.target.value);
if (number > 999.99 && number < 0.01) // throw Error or do whatever you want to do
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cheknov |
| Solution 2 | Simran Birla |
| Solution 3 | Shubham Maheshwari |
