Results 1 to 3 of 3

Thread: How can I create a function that calculate total price of products?

  1. #1
    Join Date
    Nov 2012

    Question How can I create a function that calculate total price of products?

    Hi there.

    I wanted to know how to create a function that can keep adding all the sent parameters(numbers) by user clicks.

    I'm having hard time figuring out how to create loops before writing actual calculation.

    Actually, do I even have to write any kind of loops?

    I want a page where users can see the list of products with each price on the sides, and users can click "add" button of multiple number of products, and number increases on the box called "Total Price" according to user clicks.

    Can anyone please help me??
    I'm new to JS..

  2. #2
    Join Date
    Dec 2005


    Something like this???
    <!DOCTYPE html>
    <html lang="en">
    <meta charset="utf-8" />
    <title> Product summation </title>
    <div id="priceList">
     <li> <input type="checkbox" value="1.00"> Apples ($1.00) </li>
     <li> <input type="checkbox" value="1.50"> Bananas ($1.50) </li>
     <li> <input type="checkbox" value="3.50"> Cherries ($3.50) </li>
     <li> <input type="checkbox" value="2.50"> Oranges ($2.50) </li>
     <li> <input type="checkbox" value="5.00"> Watermelon ($5.00) </li>
     <div id="priceTotal" />
    <script type="text/javascript">
    // For: http://www.webdeveloper.com/forum/showthread.php?268169-How-can-I-create-a-function-that-calculate-total-price-of-products&daysprune=30
    (function() { /* Place BELOW all <li> tags */
      var as = document.getElementById('priceList').getElementsByTagName("li");
      for( var i = 0; as[i]; i++ ) as[i].onclick = f;
      function f() {
        var sum = 0;
        var cb = document.getElementById('priceList').getElementsByTagName('input');
        for( var i=0; cb[i]; i++ ) if (cb[i].checked) { sum += cb[i].value*1; }
        document.getElementById('priceTotal').innerHTML = 'Total: $'+sum.toFixed(2);
    // Above modified from: http://www.codingforums.com/showthread.php?t=281682

  3. #3
    Join Date
    Nov 2012

    Sorry for late reply

    Thank you very much for your reply.

    That was amazing.

    And I will use and learn this script so that i can get better understanding of it.

    again, Thank you very much for your work.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center