使用Jquery计算contentEditable文本中的数字总和 [英] Calculating the sum of numbers in contentEditable text using Jquery

查看:106
本文介绍了使用Jquery计算contentEditable文本中的数字总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好了,这里是设置:我有一个表单,它的内容是我使用ContentEditable HTML属性(在表格的父元素上设置的)进行编辑的。共有四列 - 两组项目描述列和两组匹配的价格列,以及底部的区域,我希望显示总价格。

All right, here's the setup: I have a table in a "form" whose contents I'm editing using the ContentEditable HTML attribute (set on the parent element of the table). There are four columns all together-- two sets of "item description" columns and two sets of matching "price" columns, along with an area at the bottom where I'd like the for the total price to be displayed.

问题#1是我不知道如何计算不使用输入和字段的单元格之间的数字总和。复杂的事情(至少对我来说)是我用Jquery动态地向表中添加行。

Problem #1 is that I'm not sure how to calculate the sum of numbers across cells when I'm not working with inputs and fields. Complicating things (at least to me) is that I'm adding rows to the table dynamically with Jquery.

问题#2是第二组描述/价格列是可选的 - 我希望能够使用添加按钮触发这些列中的单个项目添加到总数中。

Problem #2 is that the second set of description/price columns are optional-- I'd like to be able to use an "Add" button to trigger individual items in those columns to be added to the total.

编辑:I尝试了一些随机的东西,并通过将单元格的值存储在数组中,然后告诉Jquery添加该数组的内容并输出总和,取得了一些成功。现在的问题是它没有给我一笔钱,它给了我没有空白的数组内容。例如,如果数组包含1,2,3,它会给我123而不是6。

I tried some random things and have had some success by storing the values of the cells in an array, then telling Jquery to add the contents of that array and output the sum. The problem now is that it's not giving me a sum, it's giving me the array contents without whitespace. For example, if the array contains 1,2,3 it gives me 123 instead of 6.

编辑#2:在拼凑了六个教程,我有一些适用于问题1的东西。现在问题#2!

Edit #2: After cobbling together bits and pieces of a half dozen tutorials, I've got something that works for Problem #1. Now on to problem #2!

var sumArray = []
            $('#calc').click(function(){ 
                $('table tbody tr').each(function() {
                    sumArray.push($(this).find('.cost').text().match(/\d+/));                       
                });
                var total = 0;
                for (var i = 0; i < sumArray.length; i++) {
                    total += parseInt(sumArray[i]);
                }
                $('.totalcost').text(total);

            });

以下是表格代码:

Here's the table code:

<table>
            <thead>
                <tr>
                        <th>Service</th>
                        <th>Cost</th>
                        <th>Complementary (Optional) Service</th>
                        <th>Cost</th>

                </tr>
            </thead>
            <tbody>
                <tr>
                    <td></td>
                <td class="cost"></td>
                    <td></td>
                    <td class="compcost"></td>
                </tr>
            </tbody>
            <tfoot>
                <tr>

                        <th>Total</th>
                        <th class="totalcost"></th>

                </tr>
            </tfoot>
        </table>
        <span id="add">Add</span>
        <span id="remove">Remove</span>
        <span id="reset">Reset</span>
        <span id="nocomp">No Comps</span>
        <span id="calc">Calculate Total</span>
    </div>

这里是我现在使用的JS。

And here's the JS I'm using right now.

//Add fields to table
            var i = $('tbody>tr').size() + 1;

            $('#add').click(function() {
                if ($("tbody tr:first-child td").length > 2) {
                $('<tr><td></td><td class="cost"></td><td></td><td class="compcost"></td></tr>').fadeIn('slow').appendTo('tbody');
                i++;
                }
                else
                {$('<tr><td></td><td class="cost"></td></tr>').fadeIn('slow').appendTo('tbody');
                i++;
                };

            });

            $('#remove').click(function() {
            if(i > 1) {
                $('tbody>tr:last').remove();
                i--;
            }
            });

            $('#reset').click(function() {
            while(i > 2) {
                $('tbody>tr:last').remove();
                i--;
            }
            });

            $('#nocomp').click(function(){
                if ($("tbody tr td").length > 2) {
                $('thead tr th:nth-child(2),thead tr th:nth-child(3),tbody>tr td:nth-child(2),tbody>tr td:nth-child(3)').remove();
                }
            });

        /*$('#calc').click(function(){
            $('table tbody tr').each(function() {
            $(this).find('.totalcost').text(
            parseFloat($(this).find('.cost').text())
        );
            });
        });*/

        $('#calc').click(function(){ 
            $(this).find('table tbody tr td.cost').each(function(idx)
            {
                var total = $(this).text();
                count += total;                          
            });
            alert(parseInt(count));
        });


推荐答案

看看这个jsFiddle,它可能是你想要:
http://jsfiddle.net/mPvyA/3/

Take a look at this jsFiddle, it might be what you want: http://jsfiddle.net/mPvyA/3/

我稍微修改了一下按钮来添加/删除一个包含的类,然后检查计算结果:

I modified your buttons slightly to add/remove an included class then check for that on calculate:

        $('#exccomp').click(function(){
            $('table').find('.compcost').removeClass('included');
        });

        $('#inccomp').click(function(){
            $('table').find('.compcost').addClass('included');
        });

        $('#calc').click(function(){ 
            var sumArray = [];
            $('table tbody tr').each(function() {
                var $this = $(this), 
                    includedCompCost = $this.find('.compcost').filter('.included').text().match(/\d+/);
                sumArray.push($this.find('.cost').text().match(/\d+/)); 
                if (includedCompCost !== "") { sumArray.push(includedCompCost); }
            });
            var total = 0;
            for (var i = 0; i < sumArray.length; i++) {
                var parsedInt = parseInt(sumArray[i]); 
                if (!isNaN(parsedInt) && parsedInt > 0) { 
                   total += parsedInt; 
                } 
            }
            $('.totalcost').text(total);
        });​

这篇关于使用Jquery计算contentEditable文本中的数字总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆