简体   繁体   中英

Using JavaScript to show total of an order

I have a table of items available for purchases which I am displaying on the site. I am using mysql to fetch all the items and display them in a table. Among others, the table contains this:

<input type="hidden" name="price" id="price'.$id.'">  //id is one part of MySQL query results
<input type="text" name="count_'.$id.'">

All this is displayed for around 200 items with ID being not completely in sequence (I found some JavaScript code that used for (i = 0; i < rows.length; i++) {} , however, with my IDs not being in a sequence, this is not a good option for me).

I would like to display a total of an order using JavaScript and I am not experienced when it comes to JS. I would be very thankful for your advices.

You coul duse jQuery :

function orderTotal()
{
   var total=0;
   $('input[name="price"]').each(function(){
      var price = parseFloat($(this).val());
      var amount = parseFloat($('input[name="count_'+$(this).attr('name').substring(5)+'"]').val());
      total += price+amount;
   });
   return total;
}

I suggest you wrap them in another element, lets use div . Add a class to that, lets say moneyline

<div class="moneyline">
    <input class="price" type="hidden" name="price" id="price'.$id.'">  //id is one part of MySQL query results
    <input class="quantity" type="text" name="count_'.$id.'">
</div>

Im going to give the example with jQuery, and some button to trigger it:

$('#someButton').on('click', function(){
    var total = 0;
    $('.moneyline').each(function(){
        var price = parseInt($(this).find('.price'), 10);
        var quantity = parseInt($(this).find('.quantity'), 10);
        total+= quantity*price;
    });
    alert( total );
});

Consider adding a class to each element that you want to count and see the answer below on stackoverflow. You should be able to have a counter for each occurrence of the class and show this variable in the html

How to getElementByClass instead of GetElementById with Javascript?

<div class="item"> ... <your inputs> ... </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM