dongxianghuan3587 2014-01-30 11:15
浏览 139
已采纳

使用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.

  • 写回答

3条回答 默认 最新

  • douyan8961 2014-01-30 11:41
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿