-2
foreach($products as $row){
  <input type="hidden" class="prodId" name="id" value="<?php echo $row['id']; ?>">
  <input type="hidden" class="prodUnique" name="unique" value="<?php echo $unique; ?>">
  <button id="added" onClick="addToCart()" class="button btn-cart" title="Add to Cart" type="button"><span><i class="icon-basket"></i> Add to Cart</span></button>
}

<script>
function addToCart(){
   var id = $(".prodId").val();
   var unique = $(".prodUnique").val();
   console.log(id);
}
</scritp>

Every time it is showing only first product ID. Means the id's are getting displayed properly in HTML, But When I console it in javascript, It shows same id. Suppose there are 4 products with ID 100, 101, 103, 105 displaying, then whenever I click on any product, the value every time getting consoled in javascript is 100.

Akhil Aravind
  • 5,741
  • 16
  • 35
webdev
  • 47
  • 6
  • That selector will return a list of objects that you have to loop on and get the value. – Agnibha Jul 22 '18 at 05:59
  • Because in HTML on class denotes a set of objects. Multiple element can belong to the same class. – Agnibha Jul 22 '18 at 06:00
  • Can u please show with basic code example? – webdev Jul 22 '18 at 06:01
  • Also note that you use an id as a static value in a loop. This will result in multiple elements with the same id for your button. This is not allowed in HTML as every id needs to be unique. – Mark Baijens Jul 22 '18 at 07:56
  • Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Louys Patrice Bessette Jul 22 '18 at 08:23

3 Answers3

1

You should be doing something like this,

$(".someClassSelector").each((key, element) => {
    let value = $(element).val();
    /*
        Use your logic
    */
});
Agnibha
  • 613
  • 1
  • 11
  • 20
1

forEach() is a JavaScript method.

So you are looping $products with 2 inputs and a button where the PHP has executed long ago, on the server-side... Long before the begining of the execution of the JS. That means the values are the same for each iteration of that client-side loop.

More reading on this other SO answer: https://stackoverflow.com/a/13840431/2159528

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64
1

Instead of calling function you can have click event on click of button and pick values by custom attributes. Refer code.

foreach($products as $row){
  <button id="added" prodUnique="<?php echo $unique; ?>" prodId="<?php echo $row['id']; ?>" class="button btn-cart" title="Add to Cart" type="button"><span><i class="icon-basket"></i> Add to Cart</span></button>
}

<script>
$(document).ready(function(){
    $('.added').click(function(){
        var id = $(this).attr('prodId');
        var unique = $(this).attr('prodUnique')
        console.log(id);
    });
});
</scritp>
piyush
  • 655
  • 4
  • 11