Bogdan C
Bogdan C

Reputation: 399

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.

Upvotes: 3

Views: 2070

Answers (3)

Rohit.007
Rohit.007

Reputation: 3502

Actually your Hidden field ID should be unique but it is in loop and returning the same value for all rows.

<input type="hidden" value="<?php echo $q; ?>" id="**id_part**">

Try blow changes,
change your inner html as below
<input type="button" value="-" id="minus" onclick="minus(<?php echo $row['id']; ?>)">
<input type="button" value="+" id="plus" onclick="plus(<?php echo $row['id']; ?>)">


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

Upvotes: 0

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Working fiddle.

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

Please use common classes instead.

Upvotes: 5

Tphil
Tphil

Reputation: 43

The ID id_part is being generated for every row in your script. When you click on the button it finds the instance of id_part and its first value and edits its value.

Use unique ids say id='id_part' +<?php echo $row['id']; ?>

Upvotes: 0

Related Questions