Sum/Count Values Of Checked Checkboxes & Radio Buttons

File Size: 2.41 KB
Views Total: 10459
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Sum/Count Values Of Checked Checkboxes & Radio Buttons

This is a tiny jQuery script used to summate/count the values of all checked checkboxes and/or radio buttons.

Useful for e-commercial webapp to calculate the total price based on the multiple products selected by the user.

How to use it:

1. Create a set of checkboxes and radio buttons and specify the price for each product using the value attribute as follows:

<form id="products">
  <input class="checkbox" type="checkbox"  value="1000" /> JavaScript
  <input class="checkbox" type="checkbox"  value="2000" /> HTML
  <input class="checkbox" type="checkbox"  value="3000" /> CSS
  <input class="checkbox" type="checkbox"  value="4000" /> jQuery
  <input class="checkbox" type="checkbox"  value="5000" /> Python
  <input class="checkbox" type="radio" value="1000" /> Angular
  <input class="checkbox" type="radio" value="2000" /> React
  <input class="checkbox" type="radio" value="3000" /> React Native
  <input class="checkbox" type="radio" value="4000" /> Vue.js
  <div id="price">Total Price: $ <span >0</span></div>
</form>

2. Load the required jQuery library in the document when needed:

<script src="/path/to/cdn/jquery.slim.min.js"></script>

3. The main script to count the values and display the total price in the span element.

$("#form_calc").change(function() {

  var totalPrice   = 0,
      values       = [];
      
  $('input[type=checkbox], input[type=radio]').each( function() {
    if( $(this).is(':checked') ) {
      values.push($(this).val());
      totalPrice += parseInt($(this).val());
        }
    });

  $("#price span").text(totalPrice);  
    
});

This awesome jQuery plugin is developed by Denwerpr. For more Advanced Usages, please check the demo page or visit the official website.