MariaL MariaL - 5 months ago 28
Javascript Question

Increase/ decrease value of input field with Javascript

I've added some functionality to my shopping cart to change the quantity of the products. So there is a plus and a minus button next the the quantity input field.
This is the code:

<button type="submit" id="qtyMinus" class="qtyMinus" title="<?php echo $this->__('Update') ?>" data-qty="-1"><i class="fa fa-minus"></i></button>
<input name="cart[<?php echo $_item->getId() ?>][qty]" value="<?php echo $this->getQty() ?>" size="4" id="qtyField" title="<?php echo $this->__('Qty') ?>" class="input-text qty" maxlength="12" type="text"/>


<button type="submit" id="qtyPlus" title="<?php echo $this->__('Update') ?>" class="qtyPlus" data-qty="1"><i class="fa fa-plus"></i></button>
<button type="submit" title="<?php echo $this->__('Update') ?>" class="button btn-update-qty btn-alt btn-new"><span><span class="updateNew"><?php echo $this->__('Update') ?></span></span></button>


And the jquery:

$j("#qtyPlus").click(function(){
var $n = $j("#qtyField");
$n.val( Number($n.val())+1 );
});

$j("#qtyMinus").click(function(){
var $n = $j("#qtyField");
$n.val( Number($n.val())-1 );
});


Now, this works however if more than one different product is added the buttons of the second product won't work- I assume because they've got the same id. Can anybody think of a better way of doing this or a workaround?

Answer

You can not have same id more that once in a document. Change Ids to classes and put each item in a parent wrapper:

<div class="product"> 
<button type="submit" id="qtyMinus" class="qtyMinus" title="<?php echo $this->__('Update') ?>"  data-qty="-1"><i class="fa fa-minus"></i></button>
    <input name="cart[<?php echo $_item->getId() ?>][qty]" value="<?php echo $this->getQty() ?>" size="4" id="qtyField" title="<?php echo $this->__('Qty') ?>" class="input-text qty" maxlength="12" type="text"/>


<button type="submit" class="qtyPlus" title="<?php echo $this->__('Update') ?>"  class="qtyPlus" data-qty="1"><i class="fa fa-plus"></i></button>
                        <button type="submit" title="<?php echo $this->__('Update') ?>" class="button btn-update-qty btn-alt btn-new"><span><span class="updateNew"><?php echo $this->__('Update') ?></span></span></button>
</div>

Now you can simply do this:

 $j(".qtyPlus").click(function(){
    var n=$(this).closest('.product').find('.qtyField');
    n.val( Number(n.val())+1 ); 
});