js控制table增减行 (例如:订单添加删除商品)

来源:互联网 发布:淘宝餐饮制售是什么 编辑:程序博客网 时间:2024/05/16 07:34

【html代码】

<a class="btn btn-xs btn-warning" href="javascript:void(0)" onclick="add_products();">添加商品</a><div style="width:800px;" class="user-group" data="" data-form="form[uids][]" data-multi="true" ></div><div style="min-height:150px;" class="callout"><table class="table table-bordered bg-white" id="ProductsInfoShow"><thead><tr><th style="width:5%">编号</th><th style="width:50%">商品名称</th><th style="width:10%">单价</th><th style="width:10%">购买数量</th><th style="width:15%">小计</th><th style="width:10%">操作</th></tr></thead><tbody class="tbodyProduct"><? if($detail_rows):?><? foreach ($detail_rows as $detail_row): ?><tr class="demoProduct"><td id="product_id"><input type="hidden" value="<? echo $detail_row->product_id;?>" name="product_id[]"><? echo $detail_row->product_id;?></td><td i d="product_name"><? echo $detail_row->product_name;?></td><td id="price_item_<? echo $detail_row->product_id;?>"><strong><? echo '¥'.$detail_row->price;?></strong></td><td><div class="f_l add_chose"><a class="reduce" onClick="setAmount.reduce('#qty_item_<? echo $detail_row->product_id;?>')" href="javascript:void(0)">-</a><input type="text" name="qty_item_<? echo $detail_row->product_id;?>" value=<? echo $detail_row->buy_num; ?> id="qty_item_<? echo $detail_row->product_id;?>" onKeyUp="setAmount.modify('#qty_item_<? echo $detail_row->product_id;?>')" class="text" /><a class="add" onClick="setAmount.add('#qty_item_<? echo $detail_row->product_id;?>')" href="javascript:void(0)">+</a></div></td><td><span class="total-font" id="total_item_<? echo $detail_row->product_id;?>"><? echo '¥'.($detail_row->price)*($detail_row->buy_num) ?></span></td><td><input type="button" value="[删除]" class="del" ></td></tr><? endforeach; ?><? endif ;?><tr class="all_price"><td></td><td></td><td></td><td><strong style="font-size:18px;">合计:<strong></td><td><div  class="total-rows"><em><input type="hidden" id="total_item" name="form[total_price]" value="0"/>¥<label id="all_item" name="all_price">0</label></em></div></td><td></td></tr></tbody></table></div>

【js代码】

<script src="<? echo base_url('static/js/product_pay.js') ?>"></script><script>  function add_products(){var url = 'sale/product/index/dialog';var title = '选择商品';var all_price=$("#all_item").text();;div = $(this).parent('div.user-group');//box = $(this).next('div.user-gather');single = (typeof(div.attr('data-multi'))=='undefined');window.top.art.dialog.open('sale/product/index/dialog?single='+ (single),{title:title,height:500,width:700,lock: true,ok: function () {products = this.iframe.contentWindow.$(".active");products.each(function(i,dom){id = $(dom).attr('data-uid');name = $(dom).attr('data-name');names = new Array();names = name.split("|^|");//判断添加重复性                    if ($("#price_item_"+id).length>0){                       window.top.art.dialog.tips('请不要重复添加');                        return;                    } //添加行htmlProduct = "<tr class=\"demoProduct\">"+"<td id=\"product_id\"><input type=\"hidden\" value="+id+" name=\"product_id[]\">"+id+"</td>"+"<td id=\"product_name\">"+names[0]+"</td>"+"<td id=\"price_item_"+id+"\"><strong>¥"+names[1]+"</strong></td>"+"<td><div class=\"f_l add_chose\">\<a class=\"reduce\" onClick=\"setAmount.reduce('#qty_item_"+id+"')\" href=\"javascript:void(0)\">-</a>\<input type=\"text\" name=\"qty_item_"+id+"\" value=\"1\" id=\"qty_item_"+id+"\" onKeyUp=\"setAmount.modify('#qty_item_"+id+"')\" class=\"text\" /><a class=\"add\" onClick=\"setAmount.add('#qty_item_"+id+"')\" href=\"javascript:void(0)\">+</a></div></td>"+"<td><span class=\"total-font\" id=\"total_item_"+id+"\">¥"+names[1]+"</span></td>"+"<td><input type=\"button\" value=\"[删除]\" class=\"del\" ></td></tr>";    var currentRow=$(".tbodyProduct tr:eq(0)")    currentRow.before(htmlProduct);all_price=Number(all_price) + Number(names[1]);;$("#all_item").text(all_price);$("#total_item").val(all_price);                   });                                   if (!single) return false;    },cancel: true});}            $(function(){                  region("form[province]","form[city]","form[country]");$('.tbodyProduct').on('click','.del',function (){$(this).parent().parent().remove();all_price();});            });            </script>

【product_pay.js】

/** jQuery Calculation Plug-in**/(function($) {    var defaults = {reNumbers: /(-|-\$)?(\d+(,\d{3})*(\.\d{1,})?|\.\d{1,})/g, cleanseNumber: function (v) {        return v.replace(/[^0-9.\-]/g, "");    }, useFieldPlugin: (!!$.fn.getValue), onParseError: null, onParseClear: null};    $.Calculation = {version: "0.4.07",setDefaults: function(options) {        $.extend(defaults, options);    }};    $.fn.parseNumber = function(options) {        var aValues = [];        options = $.extend(options, defaults);        this.each(function () {            var $el = $(this),sMethod = ($el.is(":input") ? (defaults.useFieldPlugin ? "getValue" : "val") : "text"),v = $.trim($el[sMethod]()).match(defaults.reNumbers, "");            if (v == null) {                v = 0;                if (jQuery.isFunction(options.onParseError)) options.onParseError.apply($el, [sMethod]);                $.data($el[0], "calcParseError", true);            } else {                v = options.cleanseNumber.apply(this, [v[0]]);                if ($.data($el[0], "calcParseError") && jQuery.isFunction(options.onParseClear)) {                    options.onParseClear.apply($el, [sMethod]);                    $.data($el[0], "calcParseError", false);                }            }            aValues.push(parseFloat(v, 10));        });        return aValues;    };    $.fn.calc = function(expr, vars, cbFormat, cbDone) {        var $this = this, exprValue = "", precision = 0, $el, parsedVars = {}, tmp, sMethod, _, bIsError = false;        for (var k in vars) {            expr = expr.replace((new RegExp("(" + k + ")", "g")), "_.$1");            if (!!vars[k] && !!vars[k].jquery) {                parsedVars[k] = vars[k].parseNumber();            } else {                parsedVars[k] = vars[k];            }        }        this.each(function (i, el) {            var p, len;            $el = $(this);            sMethod = ($el.is(":input") ? (defaults.useFieldPlugin ? "setValue" : "val") : "text");            _ = {};            for (var k in parsedVars) {                if (typeof parsedVars[k] == "number") {                    _[k] = parsedVars[k];                } else if (typeof parsedVars[k] == "string") {                    _[k] = parseFloat(parsedVars[k], 10);                } else if (!!parsedVars[k] && (parsedVars[k] instanceof Array)) {                    tmp = (parsedVars[k].length == $this.length) ? i : 0;                    _[k] = parsedVars[k][tmp];                }                if (isNaN(_[k])) _[k] = 0;                p = _[k].toString().match(/\.\d+$/gi);                len = (p) ? p[0].length - 1 : 0;                if (len > precision) precision = len;            }            try {                exprValue = eval(expr);                if (precision) exprValue = Number(exprValue.toFixed(Math.max(precision, 4)));                if (jQuery.isFunction(cbFormat)) {                    var tmp = cbFormat.apply(this, [exprValue]);                    if (!!tmp) exprValue = tmp;                }            } catch(e) {                exprValue = e;                bIsError = true;            }            $el[sMethod](exprValue.toString());        });        if (jQuery.isFunction(cbDone)) cbDone.apply(this, [this]);        return this;    };    $.each(["sum", "avg", "min", "max"], function (i, method) {        $.fn[method] = function (bind, selector) {            if (arguments.length == 0)return math[method](this.parseNumber());            var bSelOpt = selector && (selector.constructor == Object) && !(selector instanceof jQuery);            var opt = bind && bind.constructor == Object ? bind : {bind: bind || "keyup", selector: (!bSelOpt) ? selector : null, oncalc: null};            if (bSelOpt) opt = jQuery.extend(opt, selector);            if (!!opt.selector) opt.selector = $(opt.selector);            var self = this, sMethod, doCalc = function () {                var value = math[method](self.parseNumber(opt));                if (!!opt.selector) {                    sMethod = (opt.selector.is(":input") ? (defaults.useFieldPlugin ? "setValue" : "val") : "text");                    opt.selector[sMethod](value.toString());                }                if (jQuery.isFunction(opt.oncalc)) opt.oncalc.apply(self, [value, opt]);            };            doCalc();            return self.bind(opt.bind, doCalc);        }    });    var math = {sum: function (a) {        var total = 0, precision = 0;        $.each(a, function (i, v) {            var p = v.toString().match(/\.\d+$/gi), len = (p) ? p[0].length - 1 : 0;            if (len > precision) precision = len;            total += v;        });        if (precision) total = Number(total.toFixed(precision));        return total;    },avg: function (a) {        return math.sum(a) / a.length;    },min: function (a) {        return Math.min.apply(Math, a);    },max: function (a) {        return Math.max.apply(Math, a);    }};})(jQuery);/** ------------- choose -------------------- **//* 数量修改*/var setAmount = {    min:1,    max:999,    reg:function(x) {        return new RegExp("^[1-9]\\d*$").test(x);    },    amount:function(obj, mode) {        var x = $(obj).val();        if (this.reg(x)) {            if (mode) {                x++;            } else {                x--;            }        } else {            alert("请输入正确的数量!");            $(obj).val(1);            $(obj).focus();        }        return x;    },    reduce:function(obj) {        var x = this.amount(obj, false);        if (x >= this.min) {            $(obj).val(x);            recalc(obj);all_price();        } else {            alert("商品数量最少为" + this.min);            $(obj).val(1);            $(obj).focus();        }    },    add:function(obj) {        var x = this.amount(obj, true);        if (x <= this.max) {            $(obj).val(x);            recalc(obj);all_price();        } else {            alert("商品数量最多为" + this.max);            $(obj).val(999);            $(obj).focus();        }    },    modify:function(obj) {        var x = $(obj).val();        if (x < this.min || x > this.max || !this.reg(x)) {            alert("请输入正确的数量!");            $(obj).val(1);            $(obj).focus();recalc(obj);all_price();        }else{$(obj).val(x);            recalc(obj);all_price();}    }}function BuyUrl(wid) {    var pcounts = $("input[id^=qty_item_]").val();    var patrn = /^[0-9]{1,4}$/;    if (!patrn.exec(pcounts)) {        pcounts = 1;    }    else {        if (pcounts <= 0)            pcounts = 1;        if (pcounts >= 1000)            pcounts = 999;    }};/** total_item **/$(document).ready(function (obj) {    $("input[name^=qty_item_]").bind("keyup", recalc('_'));});//合计订单总价function all_price(){var _price="";var all_price=0;if($("#ProductsInfoShow").find("tr").length<=2){$("#all_item").text(0);    $("#total_item").val(0);return;}for(var i=1;i<$("#ProductsInfoShow").find("tr").length-1;i++){  _price=$("#ProductsInfoShow tr").eq(i).find("td [id^=total_item_]").text();  _price=_price.replace("¥", "");  all_price=all_price+Number(_price);  $("#all_item").text(all_price);  $("#total_item").val(all_price);}}//计算商品小计function recalc(obj) {var id = new Array();id = obj.split("_");    $("input[id^=total_item_"+id[2]+"]").val()    //产品价格统计    $("[id^=total_item_"+id[2]+"]").calc(        "qty * price",        {            qty: $("input[name^=qty_item_"+id[2]+"]"),            price: $("[id^=price_item_"+id[2]+"]")        },        function (s) {            return "¥" + s.toFixed(2);        },        function ($this) {            var sum = $this.sum();            $("[id^=total_item_"+id[2]+"]").text(                "¥" + sum.toFixed(2)            );            $("#total_price").val($("[id^=total_item_"+id[2]+"]").text());        }     );all_price();    //产品积分统计 此功能暂时不用    $("[id^=total_points]").calc(        "qty * price",        {            qty: $("input[name^=qty_item_]"),            price: $("[id^=price_item_]")        },        function (s) {            return "" + s.toFixed(0);        }    );};


【效果预览】




1 0