How to perform Dynamic Addition | Calculation using Js | jQuery

Click on the below Checkbox to perform action.

Here is the live working example of How to perform Dynamic Addition & Calculation using Js & jQuery

Html code

Html Structure for this

<div class="cell">
<div class="check">
<input id="check-0" type="checkbox" />
<label for="check-0">$100</label>
<div class="mask"></div>
</div>
</div>

<div class="cell">
<div class="check">
<input id="check-1" type="checkbox" />
<label for="check-1">$125</label>
<div class="mask"></div>
</div>
</div>

<div class="cell">
<div class="check">
<input id="check-2" type="checkbox" />
<label for="check-2">$150</label>
<div class="mask"></div>
</div>
</div>

<div id="price"></div>

Script

JS + jQuery Code

$(".cell").on("click", "input:checkbox", function () {
var $this = $(this);
var $total = $("#price");
var $target = $("label[for='" + $this.attr("id") + "']");

var item_value = +($target.html().replace("$", "") || 0);
var cur_total = +($total.html().replace("$", "") || 0);

if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}

$total.html("$" + cur_total);
});

If you are using latest jQuery Script OR If you are getting errors undefined $ Error then use code below.

JS + jQuery Code (New jQuery version Only)

jQuery(".cell").on("click", "input:checkbox", function () {
var $this = jQuery(this);
var $total = jQuery("#price");
var $target = jQuery("label[for='" + $this.attr("id") + "']");
var item_value = +($target.html().replace("$", "") || 0);
var cur_total = +($total.html().replace("$", "") || 0);
if ($this.prop("checked") === true) {
cur_total += item_value;
} else {
cur_total -= item_value;
}
$total.html("$" + cur_total);
});

That’s it. I hope you enjoyed the article. If you have questions or queries related to implementation of Dynamic Addition & Calculation using Js & jQuery then feel free to ask in the comment section below, happy to help you.

About the author

He is the Founder & Owner of Inventive9. He is a Full-stack web developer with great knowledge of SEO & Digital Marketing. He has 7+ years of experience in IT Solution Services and serving 115+ clients worldwide.

Leave a Reply