根据为多个项目编写的数量的总价格

时间:2012-11-27 20:09:09

标签: javascript html

你好我正在制作一个购物车系统但是我被困在计算总产品数量的数量我希望用户从下拉菜单中选择一个价格然后输入数量它更新总时刻同样的对于其他项目。我为这个结构做了一个js小提琴,任何人都可以通过简单的javascript帮助我实现这个目标吗?

http://jsfiddle.net/nVCY4/25/

下拉结构就像

<select id="TIPR1" class="table-select" title="Please select">
   <option value="31">Field Box $31</option>
   <option value="29">Lodge Box $29</option>
   <option value="19">Bleachers $19</option>
</select>


function CalculateTotal(frm) {
    var order_total = 0

    // Run through all the form fields
    for (var i=0; i < frm.elements.length; ++i) {

        // Get the current field
        form_field = frm.elements[i]

        // Get the field's name
        form_name = form_field.name

        // Is it a "product" field?
        if (form_name.substring(0,4) == "TIQT") {

            // If so, extract the price from the name
            //item_price = parseFloat(form_name.substring(form_name.lastIndexOf("_") + 1))
            var test = "TIPR1,TIPR2";
            //test = test + i;
            var e = document.getElementById(test);
            item_price = e.options[e.selectedIndex].value;

            // Get the quantity
            item_quantity = parseInt(form_field.value)

            // Update the order total
            if (item_quantity >= 0) {
                order_total += item_quantity * item_price
            }
        }
    }

    // Display the total rounded to two decimal places
    document.getElementById("order_total").firstChild.data = "$" + 
}

3 个答案:

答案 0 :(得分:1)

我鼓励你自己尝试一下,绝对的 最佳 学习方法,就是这样做。

如果你包含jQuery或类似的库,那就很容易了。

以下是一个示例:http://jsfiddle.net/nVCY4/26/

var selects = $('select');
var inputs = $('input');
selects.change(calculate);
inputs.keyup(calculate);

function calculate(){
    var runningTotal = 0;
    selects.each(function(i){
        var val = parseInt($(this).val());
        var qty = inputs.eq(i).val();
        runningTotal += (val*qty);
    });
    $('#grandtotal').html("Grand-total: "+runningTotal);
}​

答案 1 :(得分:0)

将您想要的逻辑添加到onchange事件中,如下所示:

<select id="TIPR1" onchange="f()" class="table-select" title="Please select">

其中f是您在选择某些内容时要调用的函数。

答案 2 :(得分:0)

这是一个可能的解决方案..实际上,有几种可能的解决方案。我不知道这些字段在整个表单的上下文中是如何看的。因此,我在下面展示的方法之一可能比另一种方法更适合您。

我只更新了你的HTML代码:我使SELECT元素上的ID唯一,这样就可以从JS中轻松调用它们。

在JS代码中,有三种不同的方法来调用字段并获取值。必须允许一个人运行。其他需要删除或注释掉。

这也适用于您设置总计值的底部。您没有提供显示订单总计的HTML。所以我提供了几种不同的样本。

此代码未经测试,并作为向您展示此问题的可能解决方案的方式提供。我至少还有10个可以想到的东西,但这些(我认为)是您提供的HTML代码示例的最佳匹配。

<div id="content">
    <table border="1">
        <tr>
            <th>Book Cover</th>
            <th>Title & Author</th>
            <th>Price</th>
            <th>Quantity</th>
        </tr>
        <tr>
            <td class="image">
                <a href="cover2.html" onClick="return openNewWindow(this.href, 475, 725);"><img alt="Book Cover" src="images/covers/2artfielding.png" /></a>
            </td>
            <td class="title">
                <p class="table"><b>The Art of Fielding</b></p>
                <p class="table"><i>by Chad Harbach</i></p>
            </td>
            <td class="price">
               <select id="TIPR1" class="table-select" title="Please select">
                    <option value="31">Field Box $31</option>
                    <option value="29">Lodge Box $29</option>
                    <option value="19">Bleachers $19</option>
                </select>
            </td>
            <td class="quantity">
                <input type="text" id="artquantity" value="1" /><br />
            </td>
        </tr>
        <tr>
            <td class="image"><a href="cover5.html" onClick="return openNewWindow(this.href,475, 725);"><img alt="Book Cover" src="images/covers/18thelovers.png" /></a></td>

            <td class="title">
                <p class="table"><b>The Lover's Dictionary</b></p>
                <p class="table"><i>by David Levithan</i></p>
            </td>
            <td class="price">
               <select id="TIPR2" class="table-select" title="Please select">
                    <option value="31">Field Box $31</option>
                    <option value="29">Lodge Box $29</option>
                    <option value="19">Bleachers $19</option>
                </select>
            </td>

            <td class="quantity">
                <input type="text" id="loverquantity" value="1" /><br />
            </td>
        </tr>

        <tr>
            <td class="image"><a href="cover4.html)" onClick="return openNewWindow(this.href,475, 725);"><img alt="Book Cover" src="images/covers/11nightcircus.png" /></a></td>
            <td class="title">
                <p class="table"><b>The Night Circus</b></p>

                <p class="table"><i>by Erin Morgenstern</i></p>
            </td>
            <td class="price">
               <select id="TIPR3" class="table-select" title="Please select">
                    <option value="31">Field Box $31</option>
                    <option value="29">Lodge Box $29</option>
                    <option value="19">Bleachers $19</option>
                </select>
            </td>
            <td class="quantity">
                <input type="text" id="nightquantity" value="1" /><br />
            </td>

        </tr>
        </table>
        <br />
        <p class="totals" id="grandtotal">Grand-total:</p>
</div>

<script type="text/javascript">
function CalculateTotal(frm) {
    var order_total = 0.00;
    var form_select, form_input;

    //*****************************************************************
    //Option 1: Call the fields directly
    //*****************************************************************
    form_select = document.getElementById("TIPR1");
    form_input = document.getElementById("artquantity");
    order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));

    form_select = document.getElementById("TIPR2");
    form_input = document.getElementById("loverquantity");
    order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));

    form_select = document.getElementById("TIPR3");
    form_input = document.getElementById("nightquantity");
    order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
    //*****************************************************************


    //*****************************************************************
    //Option 2: Create an array and loop through them
    //*****************************************************************
    var selectIDs = ["TIPR1", "TIPR2", "TIPR3"];
    var inputIDs  = ["artquantity", "loverquantity", "nightquantity"];

    foreach(var i in selectIDs) {
        form_select = document.getElementById(selectIDs[i]);
        form_input = document.getElementById(inputIDs[i]);
        order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
    }
    //*****************************************************************


    //*****************************************************************
    //Option 3: Assuming there are the same number of SELECTs as INPUTs
    //*****************************************************************
    var selects = document.getElementById("content").getElementsByTagName("select");
    var inputs  = document.getElementById("content").getElementsByTagName("input");

    foreach(var i in selects) {
        form_select = selects[i];
        form_input = inputs[i];
        order_total += (parseFloat(form_select.options[form_select.selectedIndex].value) * parseFloat(form_input.value));
    }
    //*****************************************************************


    //*****************************************************************
    //Display the total rounded to two decimal places
    //*****************************************************************
    tot_val = "$" + parseFloat(order_total).toFixed(2);

    //I don't know what "order_total" is here since you didn't show it in an example...
    // - Here is the code to set it if it's an input
    document.getElementById("order_total").value = tot_val;

    // - ...if it's a block level element like a DIV or P
    document.getElementById("order_total").innerHTML = tot_val;

    // - ...or if it's a block level child of the element
    document.getElementById("order_total").firstChild.innerHTML = tot_val;
    //*****************************************************************
}
</script>