Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

    <form id="myform">
        product1
        <input type="submit" value="+" id="add">
        <input type="text" id="qty1">
        <input type="submit value="-" id="minus">
        product2
        <input type="submit" value="+" id="add">
        <input type="text" id="qty2">
        <input type="submit value="-" id="minus">
    </form>

I'd like to increase the value of the field by one if the add button is pressed and decrease by one if minus is pressed. Also the value shouldn't get less than 0.

Is there a way to do this in jQuery?


2 Answers

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.
like image 90
Domenic Avatar answered Dec 08 '25 09:12

Domenic


Your html isn't quite valid, you have multiple elements with the same id, it should be unique. But lets say you only had one set of inputs/buttons:

$("#add").click(function(){
  var newQty = +($("#qty1").val()) + 1;
  $("#qty1").val(newQty);
});

$("#minus").click(function(){
  var newQty = +($("#qty1").val()) - 1;
  if(newQty < 0)newQty = 0;
  $("#qty1").val(newQty);
});
like image 22
JonoW Avatar answered Dec 08 '25 11:12

JonoW



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!