使用javascript检查计算总计一次复选框

时间:2015-03-10 10:09:56

标签: javascript jquery html checkbox

我正在尝试为我的网站创建一个javascript代码,以便在选中复选框后进行计算。每次我选中一个复选框时,都应该计算这些项目的总价格。

这是我的HTML代码:

<form id="orderForm" action="#" method="get">
    <section id="selectBook">
        <h2>Select books</h2>
        <?php
        include_once('database_conn.php');
        $sqlBooks = 'SELECT bookISBN, bookTitle, bookYear, catDesc,  bookPrice FROM nbc_book b inner join nbc_category c on b.catID = c.catID WHERE 1 order by bookTitle';
        $rsBooks = mysqli_query($conn, $sqlBooks);
        while ($book = mysqli_fetch_assoc($rsBooks)) {
            echo "\t<div class='item'>
                    <span class='bookTitle'>{$book['bookTitle']}</span>
                    <span class='bookYear'>{$book['bookYear']}</span>
                    <span class='catDesc'>{$book['catDesc']}</span>
                    <span class='bookPrice'>{$book['bookPrice']}</span>
                    <span class='chosen'><input type='checkbox' name='book[]' value='{$book['bookISBN']}' title='{$book['bookPrice']}' /></span>
                </div>\n";
        }
        ?>
    </section>

    <section id="collection">
        <h2>Collection method</h2>
        <p>Please select whether you want your chosen book(s) to be delivered to your home address (a charge applies for this) or whether you want to collect them yourself.</p>
        <p>
        Home address - &pound;3.99 <input type="radio" name="deliveryType" value="home" title="3.99" checked = "checked" />&nbsp; | &nbsp;
        Collect from warehouse - no charge <input type="radio"  name="deliveryType" value="trade" title="0" />
        </p>
    </section>

    <section id="checkCost">
        <h2>Total cost</h2>
        Total <input type="text" name="total" id="total" size="10" readonly="readonly" />
    </section>

代码已分为标记。

这是我目前编写的javascript代码:

var item = document.getElementsByClassName("item");
    var chkbox = document.getElementsByTagName("input");

    for(var i = 0; i < chkbox.length; i++){
        chkbox[i].onchange = function(){
            //Recalculate total
            getTotal();
        }
    }

    function getTotal(){
        var total = 0.0;

        for(var i = 1; i <= chkbox.length; i++){
            //If the checkbox is checked, add it to the total
            if(chkbox[i-1].checked){
                total = total + parseFloat(chkbox[i].value);
            }
        }

        return total;

        document.getElementById("total").innerHTML = total;
    }

我真的需要一些专家来帮助我。谢谢。

1 个答案:

答案 0 :(得分:0)

  1. getTotal()中,您在此处设置值之前返回:

    return total;
    document.getElementById("total").innerHTML = total;

  2. 使用值而不是innerHTHML设置输入。

    document.getElementById("total").setAttribute("value", total);

  3. 我必须将检查更改为parseFloat(chkbox[i-1].title)以匹配if语句

  4. <强> jsFiddle

    以上示例用于产品,第一个定价为1,第二个定义为2。