Increment number input with rules to steps

I’m trying to create number input with counting rules, for example, I want to have first 5 increment steps to be 100 units (100 – 500) and once reaching 500 change increment steps to 500.

So it will be 100, 200, 300, 400, 500, 1000, 1500, 2000...

Here is what I have tried so far, something causes the 500 step attribute trigger only when reaching 600 instead 500.

   $('input#grams_quantity').on( "change", function(){
   console.log('works');
       if($(this).val() > 400){
         $("#grams_quantity").attr('step', 500);
         console.log('500');
       }
    else{
        $("#grams_quantity").attr('step', 100);
        console.log('100');
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity" value="100" min="100">

How can I set rules to number input increment steps correctly?

29 thoughts on “Increment number input with rules to steps”

  1. It is a bit tricky to get the wanted values, because the change happens before the event is called and then it needs to take action for the next click.

    1. Why does not simply changing the increment to 500 work?

      Because of the min value and a multiple of 500. By having min="100" and step="500", the next reachable value is 600.

      Solution: Change both values, min="0" and step="500".

    2. Why do wee need another condition? Why not simply check the value 500 for turning back to step="100"?

      Because 500 is coming from two directions, one from 400 and the other from 1000.

      To get the direction you need the last value for comaprison and preventing a flipflop between the values 400 and 500.

      To keep the last take a closure over this value.

    $('input#grams_quantity').on("change", function(last) {
        return function() {
            if (+$(this).val() === 400 && last < +this.value) {
                $("#grams_quantity").attr('step', 500);
                $("#grams_quantity").attr('min', 0);
            }
    
            if (+$(this).val() === 500 && last > +this.value) {
                $("#grams_quantity").attr('step', 100);
                $("#grams_quantity").attr('min', 100);
            }
    
            last = +this.value;
        };
    }(0));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="number" step="100" name="grams_quantity" class="grams_quantity" id="grams_quantity" value="100" min="100">
    Reply

Leave a Comment