Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use javascript onclick in a while PHP loop

I am trying to plus or minus 1, a simple quantity input box, which can be different like in the picture below :

enter image description here

PHP:

$query = ...
while ($row= mysqli_fetch_array($query)) 
{
     <input type="hidden" value="<?php echo $row['id']; ?>" id="id_part">
     <input type="text" value="<?php echo $row['quantity']; ?>" id="<?php echo $row['id']; ?>_count"><br>
     <input type="button" value="-" id="minus" onclick="minus()">
     <input type="button" value="+" id="plus" onclick="plus()">
}

Javascript:

<script>
     var count = 1;
     var id = document.getElementById("id_part").value;
     var countEl = document.getElementById(id + "_count");
     function plus(){
      count++;
      countEl.value = count;
     }
     function minus(){
      if (count > 1) {
       count--;
       countEl.value = count;
      }  
     }
</script>

It doesn't work. It takes me only the first id quantity box. Can't manage to edit the second quantity box, where the id should be different. As you can see, I assigned each id tag with different names, taken from database id.

like image 559
Bogdan C Avatar asked Sep 10 '26 04:09

Bogdan C


1 Answers

Working fiddle.

That happen because you've a duplicate id's when the id attribute should be unique.

Please use common classes instead.

like image 162
Zakaria Acharki Avatar answered Sep 12 '26 16:09

Zakaria Acharki



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!