Déjà vu
Déjà vu

Reputation: 783

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.

Upvotes: 0

Views: 3019

Answers (3)

axel.michel
axel.michel

Reputation: 5764

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.

Upvotes: 1

ElendilTheTall
ElendilTheTall

Reputation: 1452

I would use change events to update a variable for each of the inputs, and make a small separate function to add them together and return the total.

Upvotes: 0

Puttu
Puttu

Reputation: 98

Take each total and add each time and put it in the place of TOtal price,

Upvotes: 0

Related Questions