tags:

views:

1371

answers:

7

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?

A: 

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);
});
JonoW
hi, I have like 10 plus and minus buttons, do I have to write the same code for every single plus and minus button or is there a way to just write it once.thanks
Ah ok, then Domenic's answer should sort you out, just need to apply these click handlers in a loop.
JonoW
A: 

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 :)

usoban
A: 

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.

Matt Sach
A: 

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

Zed
+4  A: 

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 (currentVal != NaN)
            {
                $("#qty" + i).val(currentVal + 1);
            }
        });

        $("#minus" + i).click(function()
        {
            var currentVal = parseInt($("qty" + i).val());
            if (currentVal != NaN && 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.
Domenic
Yeah, that's a better and safer version of what I was doing :)
Matt Sach
how can I generalize this to multiple fields if they all have unique ids, should I change the #add1 to sth else
I updated my answer to work on an arbitrary number of fields, assuming you name them qtyX/addX/minusX, where X is a number between 1 and `numButtons` inclusive.
Domenic
A: 

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));
});
danh
A: 

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"&gt;&lt;/script&gt;
<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

moctebain