amir
amir

Reputation:

How to increase the value of a quantity field with 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?

Upvotes: 2

Views: 24580

Answers (8)

Zed
Zed

Reputation: 57648

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);
}).

Upvotes: 0

Harry Lincoln
Harry Lincoln

Reputation: 656

Thanks so much for everyone who got involved. All I drew upon and was able to come up with this in the end, that served the site very well (it was just the css that was a pain!)

HTML:

<div id="qtybox"><label for="qty">
<venda_text id=site.quantity>
</label><input name="qty" id="qty" type="text" value="1" size="3" maxlength="2"></input>
<button id="qtyplus" onclick="return false"></button>
    <button id="qtyminus" onclick="return false"></button>

</div>

js:

jQuery(function(){
    jQuery("#qtyplus").click(function(){     
     jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) + 1 );
    });
    jQuery("#qtyminus").click(function(){
     if(jQuery('#qty').val()>1)
      jQuery(":text[name='qty']").val( Number(jQuery(":text[name='qty']").val()) - 1 );

    });
  });

CSS:

#qtybox button#qtyplus {
    background: url("../images/social_icons/elements.png") no-repeat scroll -268px -223px   
    transparent;
    border: medium none;
    cursor: pointer;
    display: block;
    float: right;
    height: 23px;
    width: 23px;
}

As you can see, I removed the values of the +'s and -'s - hated how it was rendered!

Upvotes: 0

Domenic
Domenic

Reputation: 112807

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.

Upvotes: 6

moctebain
moctebain

Reputation: 11

This is the improved response of the first aswer:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function()
{
    $(".add").click(function()
    {
        var currentVal = parseInt($(this).next(".qty").val());
        if (currentVal != NaN)
        {
            $(this).next(".qty").val(currentVal + 1);
        } 
    });

    $(".minus").click(function()
    {
        var currentVal = parseInt($(this).prev(".qty").val());
        if (currentVal != NaN)
        {
            $(this).prev(".qty").val(currentVal - 1);
        }
    });
});

</script>
</head>

<body>
    <form id="myform">
        product1
        <input type="button" value="+" id="add1" class="add" />        
        <input type="text" id="qty1" value="-1" class="qty" />        
        <input type="button" value="-" id="minus1" class="minus" /><br /><br />

        product2
        <input type="button" value="+" id="add2" class="add" />        
        <input type="text" id="qty2" value="-10" class="qty" />        
        <input type="button" value="-" id="minus2" class="minus" />

    </form>

</body>

I hope they serve.... :D

Upvotes: 1

danh
danh

Reputation: 62686

I'm a rookie, but I did it like this for integers...

<div class="quantityInput" min="-32" max="32">
    <input type="text" class="quantityText">
    <input type="button" value="+" class="quantityPlus">
    <input type="button" value="-" class="quantityMinus">
</div>

min and max attributes are optional. Then, inside jQuery(document).ready(...

$(".quantityMinus").live("click", function() {
  var qInput = $(this).parents(".quantityInput");
  var qText = qInput.find(".quantityText");
  var qValue = parseInt((qText.val())? qText.val() : 0);
  qText.val(Math.max(qValue - 1, (qInput.attr("min"))? qInput.attr("min") : -0xffff));
});

$(".quantityPlus").live("click", function() {
  var qInput = $(this).parents(".quantityInput");
  var qText = qInput.find(".quantityText");
  var qValue = parseInt((qText.val())? qText.val() : 0);
  qText.val(Math.min(qValue + 1, (qInput.attr("max"))? qInput.attr("max") : 0xffff));
});

Upvotes: 3

Matt Sach
Matt Sach

Reputation: 1170

I think this should do it:

$('#add').click(function (e) {
    var quant = $(this).next('input');
    quant.val(parseInt(quant.val(), 10) + 1);
};
$('#minus').click(function (e) {
    var quant = $(this).prev('input');
    quant.val(parseInt(quant.val(), 10) - 1);
    if (parseInt(quant.val(), 10) < 0)
    { quant.val(0); }
};

This does however depend on the relative positioning of the controls not changing.

Upvotes: 0

usoban
usoban

Reputation: 5478

First, at minus buttons, you need to have type="submit", not type="submit, but I assume that is typing mistake ;)

If you want to do that, you should change plus and minus button ids to something like 'minus-qty1', 'add-qty1', etc. to identify which input you'd like to update.

  <form id="myform">
    product1
    <input type="button" value="+" id="add-qty1" onclick="increase(this)">
    <input type="text" id="qty1">
    <input type="button" value="-" id="minus-qty1" onclick="decrease(this)">
    product2
    <input type="button" value="+" id="add-qty2" onclick="increase(this)">
    <input type="text" id="qty2">
    <input type="button" value="-" id="minus-qty2" onclick="decrease(this)">

  </form>

function increase(button)
{
 var id = $(button).attr('id');
 var fname = id.substr(3);

 var newval = parseInt($("#"+fname).val()) + 1;
 $("#" + fname).val(newval);
}


function decrease(button)
{
 var id = $(button).attr('id');
 var fname = id.substr(5);

 var newval = parseInt($("#"+fname).val()) - 1;
 $("#" + fname).val(newval);
}

I hope it works, I didn't try it :)

Upvotes: 0

JonoW
JonoW

Reputation: 14229

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);
});

Upvotes: 3

Related Questions