Search code examples
javascriptjqueryhtmlrangelimit

Controlling input number field min/max


I have these two input fields that represent a range of time (seconds), and I need to make it so the "from/min" field can't go higher than the "to/max" and viceversa.

So far I got this:

jQuery(document).ready(function(){
	jQuery('#from').on( 'input', function( ) {
			if( parseInt( jQuery('#from').val() ) >= parseInt( jQuery('#to').val() ) ) jQuery('#from').val( parseInt( jQuery('#from').val() ) - 1 );
	});
  
	jQuery('#to').on( 'input', function( ) {
			if( parseInt( jQuery('#to').val() ) <= parseInt( jQuery('#from').val() ) ) jQuery('#to').val( parseInt( jQuery('#to').val() ) + 1 );
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
From: <input type="number" min="10" step="1" id="from" value="60"><br />
To: <input type="number" min="11" step="1" id="to" value="120">

It works fine when using the field or keyboard arrows, but I can still type any number/+/- on it and go lower/higher than the other field.

I am using:

jQuery('#from, #to').on( 'keypress', function( e ) {
    e.preventDefault();
});

to prevent typing as a workaround at the moment, but I'd like to be able to type a number in while still keeping the limitation of not being able to go lower/higher than the other field

How can I do this?


Solution

  • You should call preventDefault when its match your condition to prevent it for keep (for example) increasing the value. Here, I bind to jQuery custom input event instead to make it also listen to paste event.

    jQuery(function ($) {
      $('#from').on('input', function (e) {
        var from = parseInt($(this).val(), 10)
        var to = parseInt($('#to').val(), 10)
    
        if (from >= to) {
          e.preventDefault()
          $(this).val(to -1)
        }
      })
      
      $('#to').on('input', function (e) {
        var from = parseInt($('#from').val(), 10)
        var to = parseInt($(this).val(), 10)
        
        if (to <= from) {
          e.preventDefault()
          $(this).val(from + 1)
        }
      })
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    From: <input type="number" min="10" step="1" id="from" value="60"><br />
    To: <input type="number" min="11" step="1" id="to" value="120">