jquery: set min max input in option type number

user2519913 picture user2519913 · Jun 22, 2014 · Viewed 63.4k times · Source

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?

Answer

caspian picture caspian · Jun 22, 2014

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"  />