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);
});
});
question from:
https://stackoverflow.com/questions/65922604/javascript-sum-up-selected-element-data-value-and-deduct-when-unselect 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…