Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery: set min max input in option type number

Tags:

I have this part of code

<input type="number" min="2" max="10" step="2" id="contact" oninput="new_sum">

In the field I can insert a number > 10 and < 2.

How can I limit it?

like image 683
user2519913 Avatar asked Jun 22 '14 17:06

user2519913


People also ask

How do you limit input value 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.


1 Answers

add an onchange function and set the value if it's out of the range.

 $(function () {
       $( "#numberBox" ).change(function() {
          var max = parseInt($(this).attr('max'));
          var min = parseInt($(this).attr('min'));
          if ($(this).val() > max)
          {
              $(this).val(max);
          }
          else if ($(this).val() < min)
          {
              $(this).val(min);
          }       
        }); 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="numberBox" type="number" min="2" max="10" step="2" id="contact"  />
like image 67
caspian Avatar answered Sep 21 '22 08:09

caspian