Home > Enterprise >  How to set decimal input range using javascript or html?
How to set decimal input range using javascript or html?

Time:04-22

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"  aria-label="Equipment Procurement %">
<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?

CodePudding user response:

You can check for 3 conditions, For first 2 convert number to string

  1. The max length of the string should be 6 maxlength = 6

  2. If string has decimal point then .split('.') and check the length of decimal numbers const decimal = input.split('.')[1]

  3. Check if the number is 0.01 < number < 999.99

CodePudding user response:

You have to methods to achieve the same

  1. change the input type, and set min-max values:
<input type="number" min=0.01 max=999.99 name="test"  aria-label="Equipment Procurement %">
  1. 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
})
  • Related