简体   繁体   English

html表中具有多行的特定列的总计

[英]Total of a particular column from html table having multiple rows

My Java Script Code 我的Java脚本代码

<script>
    $(function(){
        $('#addRow').click(function(){
            var html = $('#row_template').html();
            $('#dataTable').append(html);
            $(".tablerow").each(function(index) {
                $(this).html(index + 1);
            });
        });
        $('#deleteRow').click(function(){
            $('#dataTable .mychkbox:checked').parents('tr').remove();
        });
        $('#dataTable').on('change','.select-desc',function(){
            var cur_val = $(this).val();
            $(this).parents('tr').find('input[name="rate[]"]').val(cur_val);
        });
        $('#dataTable').on('keyup','input[name="qty[]"]', function(){
            var qty = +$(this).val();
            var unit = +$(this).parents('tr').find('input[name="rate[]"]').val();
            $(this).parents('tr').find('input[name="amt[]"]').val(qty*unit);
            var totamt = 0 ;
            var theTbl = document.getElementById('dataTable');

            for(var i=0;i<theTbl.length;i++)
            {
                for(var j=0;j<theTbl.rows[i].cells.length;j++)
                {
                    totamt = totamt + theTbl.rows[i].cells[4].InnerHTML;
                }
            }
        });
    });
</script>

My HTML Code is 我的HTML代码是

<!DOCTYPE html>
<html>
    <div class="left">
        <h2><span class="orange">Work Order Items</span></h2>
        <table>
            <tr>
                <td><input type="button" value="Add Row" id="addRow" /></td>
                <td><input type="button" value="Remove Row" id="deleteRow" /></td>
            </tr>
        </table>
    </div>
    <table id="dataTable" class="form" border="0" width='100%'>
        <tr>
            <td></td>
            <td>No</td>
            <td>Item Description</label></td>
            <td>Qty</td>
            <td>Rate</td>
            <td>Amount</td>
            <td>Cert No</td>
            <td>C Date</td>
        </tr>
    </table>
    <table id="row_template" style="display:none">
        <tr>
            <td><input type="checkbox" name="chk[]" class="mychkbox" /></td>
            <td class="tablerow"></td>
            <td>
               <?php
                    $sql = "SELECT itrate,CONCAT(itname,'|',itcode) as mname FROM ITMAST ";
                    $result = mysql_query($sql) or die(mysql_error());
                    echo "<select name='itname[]' id='itname' class='select-desc' >";
                    echo "<option value=''>-- Select Item --</option>";
                        while ($row = mysql_fetch_array($result)) 
                        {
                            echo "<option value = '{$row['itrate']}'";
                                if ($pitcode == $row['itrate'])
                                    echo "selected = 'selected'";
                            echo ">{$row['mname']}</option>";
                        }
                        echo "</select>";
                ?>
            </td>
            <td><input type="text" name="qty[]" id="qty" size="6" class='rightJustified'></td>
            <td><input type="text" name="rate[]" id="rate" size="8" class='rightJustified' readonly></td>
            <td><input type="text" name="amt[]" id="amt" size="9" class='rightJustified' readonly></td>
            <td><input type="text" maxlength="10" size="8" name="txtcertno[]"></td>
            <td><input type="date" maxlength="10" size="10" name="txtcdate[]"></td>
        </tr>
    </table>
</html>

I am trying to take total of amount column ie amt[] after each entry of a row, but I am not getting it properly, I have written Javascript function for the same but some thing may be wrong in it 我试图在每行输入后取总计列即amt [],但是我没有正确地获取它,我为相同的语言编写了Javascript函数,但是其中有些地方可能是错误的

First to point out a few mistakes: 首先要指出一些错误:

  • $('#row_template').html() : browsers automatically add tbody to the table, so you end up having multiple tbody in your main table which of course won't cause any problem on its own, if that's the desired output. $('#row_template').html() :浏览器会自动将tbody添加到表中,因此您最终会在主表中拥有多个tbody ,如果这是所需的输出,那么当然不会单独出现任何问题。
  • You're misusing ID . 您正在滥用ID Each tr has multiple td with input s that share the same ID . 每个tr都有多个td ,它们的input s共享相同的ID Instead you should use class . 相反,您应该使用class
  • To calculate the total amount you're getting the innerHTML of the cells which don't hold a number, but an input element. 要计算总量,您需要获取不包含数字但包含input元素的单元格的innerHTML Instead you want the value these input elements are holding. 相反,您需要这些input元素保留的值。
  • You need to convert the values to numbers before doing math on them, otherwise it will assume they're string and just put them beside each other. 在对它们进行数学运算之前,您需要将这些值转换为数字,否则它将假定它们是字符串,并且只是将它们放置在一起。 (eg 0+1+2 = 012 and not 3). (例如0 + 1 + 2 = 012,而不是3)。 You should use parseInt or parseFlout which the latter suits this case better. 您应该使用parseIntparseFlout ,后者更适合这种情况。

A few modifications to your code: 对您的代码进行了一些修改:

 $('#addRow').click(function () {
     var html = $('#row_template tbody').html();
     $('#dataTable tbody').append(html);

And - since you're using jQuery - I completely changed the calculation to a jQuery version: 而且-由于您使用的是jQuery-我将计算完全更改为jQuery版本:

//gt(0) cause the first row contains headers
//eq(5) cause we want the 6th cell (Amount)
var totamt = 0;
$('#dataTable tr:gt(0)').each(function() {
    var newAmt = $(this).find('td:eq(5) input[type=text]').val();
    totamt += parseFloat(newAmt);
});

I did not correct all of your mistakes, You should check @Samurai answer for more details (such as use of the 'id' and other things) 我没有纠正您的所有错误,您应该查看@Samurai答案以了解更多详细信息(例如使用'id'和其他内容)

Main problem was, as I said in comment, use of innerHTML which returned " 正如我在评论中所说,主要问题是使用innerHTML并返回了“

another thing, your theTbl var was not good, you could never call .length on it. 另一件事,您的theTbl var不好,您永远都不能调用.length。 To solve that, you had to handle it this way : 为了解决这个问题,您必须采用以下方式处理:

var totamt = 0 ;
var theTbl = $('#dataTable');
//You are using jquery, so use jquery selectors...
var trs = theTbl.find("input[name='amt[]']");
//find there the AMT[] INPUTS, not the rows...
console.log("how many amt inputs? : "+trs.length);
for(var i=0;i<trs.length;i++)
{
    //fetch the inputs, and make your calculations here
    console.log("amount from row "+i+" = "+trs[i].value);
    //do not forget, as Samurai said, to convert html to numeric...
    $("#total").html(totamt+=parseFloat(trs[i].value));         
}

Here is a working solution : 这是一个可行的解决方案:

http://jsfiddle.net/nxm0ye54/20/ http://jsfiddle.net/nxm0ye54/20/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM