Lynx Lynx - 1 year ago 76
Javascript Question

Create quote summary of calculated fields

I have a form that allows users calculate cost of services. I can use the form to output the total price of the selected services via checkbox and input values * the data-price. However, I would also like to create a summary of the services they selected.

I sample of the results I am trying to achieve from my provided fiddle:

This assumes Text 1 has an input of 3 and the first two checkboxes are checked

Text 1 $29.85
Checkbox 1 $19.90
Checkbox 1 $45.95
Total $95.70

I want to use a data attribute (like how I use data-price) inside the input and checkbox fields due to the actual complex of my input labels.

Answer Source

You can add a data-name attribute to the inputs so that we know what name to display in the summary. Then, with a div with id quote-summary in your HTML, you can use this JS function to calculate the sum and display the summary:

function calculateSum() {
  var summary = [];
  var sum = 0;
  $("input.quote-input, .special-input:checked").each(function() {
    if ($(this).prop('checked') || (!isNaN(this.value) && this.value.length !== 0)) {
      var multiplier = $(this).prop('checked') ? 1 : parseFloat(this.value);
      var price = parseFloat($(this).data('price')) * multiplier;
      var name = $(this).data('name');
      sum += price;
      summary.push(name + '\t$' + price.toFixed(2));


Here's a Fiddle:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download