简体   繁体   中英

Calculating total price using javascript

I made a little form to test some things in, but i've come across a little problem i don't really know how to solve.

I made input fields and a price that changes when the user inputs a different number using javascript, which looks like this:

function changeTotalFromCount(input) {
    var unitPrice = parseFloat(input.getAttribute("data-unitPrice"));
    var count = input.value;

    var price = unitPrice * count;
    var formattedPrice = '\u20ac ' + price.toFixed(2);

    var label = input.parentNode.nextElementSibling;
    label.innerHTML = '';
    if (count != ''){
        label.appendChild(document.createTextNode(formattedPrice));
    } else {
        label.appendChild(document.createTextNode(''));
    }
}

I have around 10 products in my form which i take out of my array like this:

<?php foreach($productsData as $productData):?>
    <tr>
        <td><?php echo $productData['product']?></td>
        <td>&#8364; <?php echo $productData['price']?></td>
        <td><input type="number" id="count<?php echo $productData['code']?>" class="formnumbers" name="<?php echo $productData['name']?>" onChange="validateForm(this);changeTotalFromCount(this);" min="1" max="99"  data-unitprice="<?php echo $productData['price']?>"/></td>
        <td><span id="total<?php echo $productData['code']?>"></span></td>
    </tr>
<?php endforeach;?>

My array looks like this:

<?php
    $productsData = array(
        array( 'product' => 'Pizza Margherita',         'code' => 'Margherita',         'name' => 'PizzaMargherita',        'price' => '7.00'),
        array( 'product' => 'Pizza Fungi',              'code' => 'Fungi',              'name' => 'PizzaFungi',             'price' => '8.00'),
        array( 'product' => 'Pizza Hawai',              'code' => 'Hawai',              'name' => 'PizzaHawai',             'price' => '9.00'),
        array( 'product' => 'Pizza QuattroStagioni',    'code' => 'QuattroStagioni',    'name' => 'PizzaQuattroStagioni',   'price' => '11.00'),
        array( 'product' => 'Pizza Calzone',            'code' => 'Calzone',            'name' => 'PizzaCalzone',           'price' => '13.00'),
        array( 'product' => 'Broodje Shoarma',          'code' => 'BroodjeShoarma',     'name' => 'BroodjeShoarma',         'price' => '5.00'),
        array( 'product' => 'Broodje Doner',            'code' => 'BroodjeDoner',       'name' => 'BroodjeDoner',           'price' => '5.50'),
        array( 'product' => 'Durum Doner',              'code' => 'DurumDoner',         'name' => 'DurumDoner',             'price' => '6.00'),
        array( 'product' => 'Knoflook Saus',            'code' => 'KnoflookSaus',       'name' => 'KnoflookSaus',           'price' => '0.50'),
        array( 'product' => 'Whiskey Saus',             'code' => 'WhiskeySaus',        'name' => 'WhiskeySaus',            'price' => '0.50'),
        array( 'product' => 'Sambal Saus',              'code' => 'SambalSaus',         'name' => 'SambalSaus',             'price' => '0.50')
     );
?>

This works all fine, but i need a total price, which will display at the bottom, and when the user say adds 1 product that costs $ 7.00 it will say 7, but when the user order 2 products that cost $ 10.00 it will change to $ 27.00

I hope i made my question clear, if not please tell me!

A small JSFiddle so you understand whats happeneing: http://jsfiddle.net/ygHSC/

In this example i didn't take out all my products with my array but i hope you get what i'm trying to do.

You need a method with some kind of a loop over all your input fields, just like the one you created for one field, and trigger the call each time one field is updated:

function getTotalPrice() {
  var total = 0,
      inputs = document.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; i++) {
    if(inputs[i].value) {
      total += parseFloat(inputs[i].getAttribute("data-unitPrice")) * 
               parseInt(inputs[i].value,10);
    }
  }
  if(total > 0) {
    document.getElementById('TARGET').innerText = '\u20ac ' + total.toFixed(2);
  }
}

An updated fiddle is here .

取每个总数,每次相加,放在总价的位置,

我将使用change事件来更新每个输入的变量,并制作一个小的单独函数以将它们加在一起并返回总数。

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