to restrict the textbox to integer only. However, I was wonde...">

Only input field with limited range

I know you can use <input type="number">

to restrict the textbox to integer only. However, I was wondering if there is a way to limit this limitation? The limiting factor is no javascript function to check on each keyup

. It seems a little heavy and unnecessary. I would have thought HTML5 has something built in to take care of this edge case, but I couldn't find anything.

For example, I have an input field for deduplication rate where I want to restrict the user to number inputs (integer or float) between 3 and 7.

I have a dropdown for choosing options currently with whole and half numbers, but that doesn't provide the level of detail that I'm looking for.

+3


source to share


3 answers


As I mentioned earlier in the comments ... there is nothing here but HTML (you might think it should be). But ... since you have included Javascript and jQuery in your question, I will provide this simple and lightweight solution.

Assuming this HTML ...

<form>
  <input type="number" min="3" max="7" step="0.5"></input>
</form>

      



We can then use this script to handle our requirements.

$( document ).ready(function() {
    $('input').change(function() {
      var n = $('input').val();
      if (n < 3)
        $('input').val(3);
      if (n > 7)
        $('input').val(7);
    });
});

      

Basically, after the change event fires, we do a quick check to make sure the values ​​are within the guidelines, and if not, force them back into the range.

+3


source


<input type="number" min="3" max="7" step="0.01"></input>

      



step

helps to limit the dimension of the minimum number.

+2


source


Here's a simple solution to validate that the input is an integer contained in a given range using the HTML5 Constraint Validation API that is supported by most browsers:

<label for="n">Enter integer number 1&le;n&le;10</label>
<input type="number" min="1" max="10" step="1" id="n" oninput="(validity.valid)||(value='');">
      

Run code


To check and avtokorrektirovat input depending on the state of reality rangeOverflow

, rangeUnderflow

, stepMismatch

:

<label for="numberSize">Enter integral number 1&le;n&le;10</label>
<input type="number" min="1" max="10" id="numberSize" oninput="(!validity.rangeOverflow||(value=10)) && (!validity.rangeUnderflow||(value=1)) &&
(!validity.stepMismatch||(value=parseInt(this.value)));">
      

Run code


This will send

  • all inputs> max to max
  • Inputs <min to min

and truncate decimal values.

0


source







All Articles