Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

javascript - How to make js for calculating the price in the basket


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your markup was not conducive to a clear answer so I pared it down and added a second checkbox to use as an example. Since you used it, I add jQuery to the snippet.

  1. I added a parent "myproduct" class
  2. When checkbox value CHANGES, I handle that event for every CHECKED checkbox.
  3. I added a "price" class element with data attribute to hold the price value data-product-price="34.29" - allows me to format the text of the element with $ for instance. This could well be on the checkbox - even as the actual "value" but kept it for your example code.
  4. I made an assumption prices could be a currency value with two decimal places since you provided none so I parsed that way instead of an integer value.
  5. Loop through the checked boxes and put the total of them all.

let boxes = $('input[type=checkbox].mything')
let totalPrice = $('#totalPrice');

boxes.on('change', function() {
  let boxesPrice = 0;
  boxes.filter(':checked').each(function() {
    let productPrice = $(this)
      .closest('.myproduct')
      .find('.price')
      .data("product-price");
    boxesPrice += parseFloat(productPrice);
  });

  totalPrice.text(boxesPrice.toFixed(2));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="totalPrice"></span>

<form action="/order">
  <div class="myproduct">
    Product #<span>fun guys</span>
    <p>
      Price : <span class="price" data-product-price="34.29">$34.29</span>
    </p>
    <div>
      <input class="mything" type="checkbox" value="" />
    </div>
  </div>
  <div class="myproduct">
    Product #<span>carrots</span>
    <p>
      Price : <span class="price" data-product-price="7.84">$7.84</span>
    </p>
    <div>
      <input class="mything" type="checkbox" value="" />
    </div>
  </div>
  <input name="submit" type="submit" value="Make order" />
</form>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...