Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML number input min and max not working properly

Tags:

html

I have type=number input field and I have set min and max values for it:

<input type="number" min="0" max="23" value="14"> 

When I change the time in the rendered UI using the little arrows on the right-hand side of the input field, everything works properly - I cannot go either above 23 or below 0. However, when I enter the numbers manually (using the keyboard), then neither of the restrictions has effect.

Is there a way to prevent anybody from entering whatever number they want?

like image 250
Tomas Dohnal Avatar asked Oct 04 '15 17:10

Tomas Dohnal


People also ask

Why is input Maxlength not working?

In my experience most issues where people are asking why maxlength is ignored is because the user is allowed to input more than the "allowed" number of characters. As other comments have stated, type="number" inputs do not have a maxlength attribute and, instead, have a min and max attribute.

How do I force a number input in HTML?

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 you put limits on input type numbers in HTML?

The HTML <input> tag is used to get user input in HTML. To give a limit to the input field, use the min and max attributes, which is to specify a maximum and minimum value for an input field respectively. To limit the number of characters, use the maxlength attribute.


2 Answers

Maybe Instead of using the "number" type you could use the "range" type which would restrict the user from entering in numbers because it uses a slide bar and if you wanted to configure it to show the current number just use JavaScript

like image 133
George Wilson Avatar answered Oct 05 '22 00:10

George Wilson


With HTML5 max and min, you can only restrict the values to enter numerals. But you need to use JavaScript or jQuery to do this kind of change. One idea I have is using data- attributes and save the old value:

$(function () {    $("input").keydown(function () {      // Save old value.      if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))      $(this).data("old", $(this).val());    });    $("input").keyup(function () {      // Check correct, else revert back to old value.      if (!$(this).val() || (parseInt($(this).val()) <= 11 && parseInt($(this).val()) >= 0))        ;      else        $(this).val($(this).data("old"));    });  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <input type="number" min="0" max="23" value="14" />
like image 28
Praveen Kumar Purushothaman Avatar answered Oct 05 '22 01:10

Praveen Kumar Purushothaman