I have 3 div which are item1, item2, and item3.
item1 with <data-price="10">, item1 with <data-price="20">, item1 with <data-price="30">
What I’m trying to do is when selected the item, it will get the item’s <data-price> and sum up, while if unselect the selected item, it will remove/deduct the <data-price>.
But my code result only shows the selected item instead of summing up.
This is my HTML code:
<div id="container2">
<div class="row">
<div class="col-md-3"><div id="item1" class="select_itm" data-item="1" data-price="10">Item 1 [Price = 10]</div></div>
<div class="col-md-3"><div id="item2" class="select_itm" data-item="2" data-price="20">Item 2 [Price = 20]</div></div>
<div class="col-md-3"><div id="item3" class="select_itm" data-item="3" data-price="30">Item 3 [Price = 30]</div></div>
</div>
</div>
<br>
<br>
<div>
<p>Total Price: <span id="display">0</span></p>
</div>
This is my Javascript code:
$(document).ready(function() {
var image_selected = new Array();
$('#container2').on('click', ".select_itm", function () {
var aa = $(this)
if (!aa.is('.checked')){
aa.addClass('checked');
var myprice = this.getAttribute('data-price');
image_selected.push(myprice);
} else {
aa.removeClass('checked');
var myprice=this.getAttribute('data-price');
var index = image_selected.indexOf(myprice);
if (index > -1) {
image_selected.splice(index, 1);
}
}
var price = 0;
price += image_selected;
$('#display').html(price);
});
});
Advertisement
Answer
Simple way is to use checked class to loop through the checked elements
- Also
is('.checked')may work butis(':checked')works with inputs checkbox/radio and to check for classes you can useif($(selector).hasClass('checked'))checked here can be any class you need to check for
$(document).ready(function() {
$('#container2').on('click', ".select_itm", function () {
var aa = $(this), price = 0;
aa.toggleClass('checked'); // toggle the class checked on click
$(".select_itm.checked").each(function(){ // loop through the checked items
price += parseInt($(this).data('price')); // get total price of checked items
});
$('#display').html(price);
});
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container2">
<div class="row">
<div class="col-md-3"><div id="item1" class="select_itm" data-item="1" data-price="10">Item 1 [Price = 10]</div></div>
<div class="col-md-3"><div id="item2" class="select_itm" data-item="2" data-price="20">Item 2 [Price = 20]</div></div>
<div class="col-md-3"><div id="item3" class="select_itm" data-item="3" data-price="30">Item 3 [Price = 30]</div></div>
</div>
</div>
<br>
<br>
<div>
<p>Total Price: <span id="display">0</span></p>
</div>Note: The parseInt() function parses a string argument and returns an integer with parseInt 1 + 1 = 2 without it "1" + "1" = "11" .. So keep this in mind