1

So I am trying to validate items in my cart, by hiding the add button whenever a user's item quantity is more than the stock, the code works fine whenever there is one item in it, however when there is multiple items, my stock variable only gets the last item's stock in the cart, not all of them

This is my code below

$('.quantity-val').each(function() {
                var initialQuantity = parseInt($(this).text());
                if (initialQuantity === 0) {
                    $(this).siblings('.fa-minus-circle').hide();
                }

                var quantity = '<?php echo $details['stock'] ?>';

                console.log(initialQuantity);
                console.log(quantity);

                if (initialQuantity == quantity) {
                    $(this).siblings('.fa-plus-circle').hide();
                }

            });

I believe I would need to make the quantity variable specific but not sure how to..

Any help would be greatly appreciated!

SOLUTION

I cant answer this as its been marked duplicate (which it isnt), but I give the quantity-val classes a data attribute like so data-stock="{{ $details['stock'] }}" and then changed my variable in my JS function to

var stock_quantity = $(this).attr('data-stock');


                if (initialQuantity == stock_quantity) {
                    $(this).siblings('.fa-plus-circle').hide();
                }
John
  • 61
  • 1
  • 8

1 Answers1

0

You can not put PHP inside of JS. This would only work if you put your JavaScript inside a <script> tag in your .php file. If you would like to extract your JavaScript to a separate .js file, I suggest to store your PHP value in a global variable and access it within JS

<script>
  window.quantity = <?= $details['stock'] ?>
</script>
var quantity = window.quantity;
marcobiedermann
  • 4,317
  • 3
  • 24
  • 37