Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number only input box with range restriction

I know that you can use <input type="number"> to restrict a text box to integer only input. However, I was wondering if there is a possibility of range restricting this as well? The limiting factor being without using a javascript function to check it on every keyup. That seems a little heavy and unnecessary. I would think HTML5 would have something built in to take care of this edge-case, but I haven't been able to find anything.

For example, I have an input box for a deduplication ratio where I want to restrict the user to inputting numbers (integer or float) between 3 and 7.

I have a option-select dropdown currently with whole and half numbers, but this does not provide the level of detail I'm looking for.

like image 868
99ProblemsAndTheyreAllCode Avatar asked Jun 19 '15 22:06

99ProblemsAndTheyreAllCode


People also ask

How do I restrict input fields with only numbers?

To limit an HTML input box to accept numeric input, use the <input type="number">. With this, you will get a numeric input field.

How do I allow only the numeric value in a text box?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I restrict a textbox?

_%+-]+@[a-z0-9. -]+\. [a-z]{2,3}$"> will restrict the allowed characters according that RegExp pattern (in this case: valid-looking email addresses). The title attribute will be used as a warning / notification when the user tries to submit the data not matching the requirement.


1 Answers

As I mentioned in the comments earlier... there isn't anything that is HTML only here (you'd think there should be). But... since you did include Javascript and jQuery in your question, I'll propose this simple and light solution.

Assuming this HTML...

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

Then we can 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 within range.

like image 105
Charlie74 Avatar answered Oct 03 '22 14:10

Charlie74