How to increase the value of a quantity field with jQuery?

前端 未结 8 964
北荒
北荒 2021-01-07 05:25

I have a form with some quantity field and a plus and minus sign on each side,

    
product1
相关标签:
8条回答
  • 2021-01-07 06:06

    First of all, type="submit" should be type="button" in all cases. Also, you cannot have two elements with the same ID; I assume you want add1, minus1, add2, minus2, etc.

    The following jQuery code should work great.

    $(function () {
        var numButtons = 10;
        for (var i = 1; i <= numButtons; ++i) {
            $("#add" + i).click(function () {
                var currentVal = parseInt($("#qty" + i).val());
                if (!isNaN(currentVal)) {
                    $("#qty" + i).val(currentVal + 1);
                }
            });
    
            $("#minus" + i).click(function () {
                var currentVal = parseInt($("qty" + i).val());
                if (!isNaN(currentVal) && currentVal > 0) {
                    $("#qty" + i).val(currentVal - 1);
                }
            });
        }
    });
    

    Worth noting:

    • I wrap everything in a $(function() { ... }) call so that you attach the event handlers only after the page loads. (Specifically, after the DomContentLoaded event.) This prevents errors about how an object with the ID "add1" doesn't exist or whatever, because technically that object doesn't exist until the page actually loads.
    • Checks for NaN handles the case of the user typing non-numeric stuff into the field. You could add your own logic for that in particular, e.g. auto-convert non-numeric properties to 0 whenever someone clicks add or minus.
    0 讨论(0)
  • 2021-01-07 06:09

    You should use unique id's for all your inputs, e.g. qty1_add, qty1_minus. Then you can attach the click event to these buttons:

    $("#qty1_add").click( function() {
       $("#qty1").val( parseInt($("#qty1").val()) + 1);
    }).
    
    0 讨论(0)
提交回复
热议问题