javascript sum up selected element data value and deduct when unselect

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 and sum up, while if unselect the selected item, it will remove/deduct the .

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>
        <p>Total Price: <span id="display">0</span></p>

This is my Javascript code:

$(document).ready(function() {
var image_selected = new Array();
$('#container2').on('click', ".select_itm", function () {
        var aa = $(this)
        if( !'.checked')){
                    var myprice = this.getAttribute('data-price');
        } else {
          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;

92 thoughts on “javascript sum up selected element data value and deduct when unselect”

Leave a Comment