Search code examples
javascriptjqueryinputpreventdefault

Number Input Field Keeps Increasing after e.preventDefault()


Listening to a 'click' event on an input element with type="number" and if the e.currentTarget.value is greater than a certain value I would like to stop the input from increasing.

I used e.preventDefault() however the input continues to increase value. I also tried e.stopImmediatePropagation() and the input continued to increase the value. I also check the value of e.cancelable and it is true. Also when logging the event, the properties isDefaultPrevented and isPropagationStopped are both true.

Another solution I tried was to just set the value of the input back to the old value but then for a split second it changed, which is undesirable.

Does anyone know why this is happening?

// @method setFocus sets focus on input when clicked. Needed as FF won't focus if quantity is updated from spinners
// @return {Void}
,   setFocus: function setFocus (e)
{

    var value = parseInt(e.currentTarget.value, 10)
    , qty_avail = this.model.getStockInfo().stock
    , $input_quantity = this.$('[name="quantity"]');

    if(value > qty_avail)
    {

        e.preventDefault();
        this.$('.product-details-quantity-alert').html("There is only " + qty_avail + " piece(s) available with these options");
        this.$('.product-details-quantity-alert').css("display", "initial");

    }
    else
    {
        this.$('.product-details-quantity-alert').css("display", "none");
        $input_quantity.focus();
    }

    console.log(qty_avail);
    console.log(value);

}

Solution

  • input type="number" has max and min attribute that can be set, you can set the max attribute to constrain the element from increasing beyond a specified number. This can be achieved using HTML as below

    <input id="quantity" type="number" name="quantity" min="0" max="100" >
    

    You can also update the max attribute on the fly using javascript (for example the javascript code below changes max to 90)

    document.getElementById("quantity").setAttribute("max",90);
    

    Consider the third option below

    <input type="number" name="quantity" id="quantity" />
    
    <script>
    var myinput = $("#quantity")
    
    myinput.on('input',restrictMax)
    function restrictMax(){
        //set Maximum to 5
        var max = 5;
        var value = parseFloat($(this).val())
        if($(this).val() > max){
            $(this).val(max)
        }
     }
    </script>
    

    You can also check the JSFiddle

    Hope this helps