The HTML comes with an argument called data-{SOME-NAME} which can hold arbitrary data for a tag.

In your case, I’ve used the data-price to store the price value, and the data-quantity to store the quantity value.

Then the jQuery comes with a method called data that accepts as an argument the right part of the data attribute.

So for example, for the data-price I’ve used the data method as data('price') and for the data-quantity I’ve used the data('quantity').

Worth mentioned, that JavaScript comes also with its own implementation to get the data from a data- attribute.

So, for example, if you used the native javascript implementation for the same results the code should be like that:

let buttons = document.querySelectorAll('.button');

if ( buttons ) {
    buttons.forEach(
        function(button) {
            let price = button.querySelector('.price');
            let quantity = button.querySelector('.quantity');
    
            console.log('Price :', price.dataset.price)
            console.log('Quantity :', quantity.dataset.quantity)
        }
    );
} 

(The above code snippet, is written from my mind. I didn’t test it on my console, so it’s possible to contain errors. But generally speaking, this is how it looks like the native solution 🙂 )

let topSalePrice = $("#topSalePrice");
let topRegPrice = $("#topRegPrice");
let quantity = $(".quantity");
let price = $(".price");
let button = $(".button")

let topPrice = topSalePrice.data('price');
let regularPrice = topRegPrice.data('price');
console.log('Top Sale Price: ' + topPrice);
console.log('Top Regular Price: ' + regularPrice);

button.each(function() {
  $(this).click(
    function() {
      // Here, what I do, is to Query the DOM to find inside the Button, the two elements. The .price and the .quantity.
      let price = $(this).find('.price').first().data('price');
      let quantity = $(this).find('.quantity').first().data('quantity');

      newPrice = price * quantity;
      console.log("New Price = " + newPrice);
    }
  )
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Sale Price
<div 
  id="topSalePrice"
  data-price='9.99'
>
  9,99€
</div>

Regular Price
<div 
  id="topRegPrice"
  data-price='7.99'
>
  7,99€
</div>

<div class="button">
  <div 
    class="quantity"
    data-quantity="1"
  >
    1
  </div>
  <div 
    class="price"
    data-price='7.99'
  >
    7,99€
  </div>
</div>
<div class="button">
  <div 
    class="quantity"
    data-quantity="2"
  >
    2
  </div>
  <div 
    class="price"
    data-price='6.99'
  >
    6,99€
  </div>
</div>
<div class="button">
  <div 
    class="quantity"
    data-quantity="3"
  >3</div>
  <div 
    class="price"
    data-price='5.99'
  >
    5,99€
  </div>
</div>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top