Fahad Almehaini Fahad Almehaini - 2 months ago 28
HTML Question

PHP plus/minus button does not work properly

I have a cart page, and there is a plus minus button for quantity with each item on the page.

When i click on the first items plus/minus button it works fine but when i click on the second items buttons, then buttons works and it changes the quantity on the first items quantity input and does not update quantity either for the 1st or the second item but changes the number only.

enter image description here

CODE

<iframe name="quantity" style="display:none;"></iframe>

<form action="checkout_qty_update.php" method="post" target="quantity">
<input type="hidden" value="<?php echo $prITTD; ?>" name="hiddenID">
<input style="font-size:21px;" type="submit" value="-" onclick='javascript: subtractQty();' class="minus">
<input id="number" type="number" value="<?php echo $qtyT; ?>" class="qty" name="picpac"/>
<input style="font-size:21px;" type="submit" value="+" onclick='javascript: document.getElementById("number").value++;' class="plus">
</form>


JS for plus/minus

function subtractQty(){
if(document.getElementById("number").value - 1 < 1)
return;
else
document.getElementById("number").value--;
}

Answer

I'm pretty sure that's because all your inputs type number have the same ID number.

Try changing your HTML code like this

<form action="checkout_qty_update.php" method="post" target="quantity">
  <input type="hidden" value="<?php echo $prITTD; ?>" name="hiddenID">
  <input [...] onclick="javascript: subtractQty('<?php echo $prITTD; ?>');" >
  <input [...] id="number_<?php echo $prITTD; ?>" />
  <input [...] onclick="javascript: document.getElementById('number_<?php echo $prITTD; ?>').value++;">
</form>

And your JS code

function subtractQty(prITTD){
  var pr = document.getElementById("number_" + prITTD);
  if (pr.value - 1 < 1)
    return;
  else
    pr.value--;
}