打赏

jqgrid 表格中筛选条件的多选下拉,树形下拉 ;文本框清除插件;高级查询多条件动态筛选插件[自主开发]

 

/**
 * @@desc    文本框清除按钮,如果isAutoWrap为false当前文本框父级必须是relative定位,boostrap参考input-group
 * @@author  Bear.Tirisfal <571115139#qq.com>
 * @@since   2018-08-21
**/
; (function ($) {
    $.fn.extend({
        addClearBtn: function (options, $o) {
            var deft = {
                symbolClass: "fa fa-close",
                closeSymbol: "",
                color: "#CCC",
                display: "display:inline-block",
                fullwidth: true,
                top: -1,
                right: 8,
                isAutoWrap: true,
                returnFocus: true,
                showOnLoad: false,
                onClear: null
            };
            function getBtnTop(inputHeight, btnHeight) {
                var inputMiddle = inputHeight / 2;
                var btnMiddle = btnHeight / 2;
                return inputMiddle - btnMiddle;
            };
            if (!$o)
                $o = this;

            return $o.each(function () {
                var $input = $(this);
                if ($input.data("clear-enable-finish") === true) return this;
                var opt = cloneByObj($.extend(deft, options));

                var dataPrefx = "clear-";
                $.each(opt, function (key, val) {
                    var dataSettingval = $input.data(dataPrefx + key.toLowerCase());
                    if (dataSettingval !== undefined && val !== dataSettingval) {
                        opt[key] = dataSettingval;
                    }
                });

                if (opt.isAutoWrap === true) {
                    var stl = ["position:relative"];
                    if (opt.fullwidth === true)
                        stl.push("width:100%");
                    if (opt.display)
                        stl.push(opt.display);

                    $input.wrap("<span style='" + stl.join(";") + "' class='add-clear-span'>");
                }
                var $clearBtn = $("<a class='" + opt.symbolClass + "'>" + opt.closeSymbol + "</a>");
                $input.after($clearBtn);

                $clearBtn.css({
                    color: opt.color,
                    'text-decoration': 'none',
                    'z-index': 9,
                    display: 'none',
                    overflow: 'hidden',
                    position: 'absolute',
                    right: opt.right,
                    top: opt.top < 0
                        ? getBtnTop($input.outerHeight(), 13)
                        : opt.top
                },
                    this);

                if ($input.val().length >= 1 && opt.showOnLoad === true) {
                    $clearBtn.show();
                }

                $input.on("keyup",
                    function () {
                        if ($input.val().length >= 1) {
                            $clearBtn.show();
                        } else {
                            $clearBtn.hide();
                        }
                    });

                $input.on("paste",
                    function (e) {
                        var pastedText = "";
                        if (window.clipboardData && window.clipboardData.getData) { // IE
                            pastedText = window.clipboardData.getData('Text');
                        } else {
                            pastedText = e.originalEvent.clipboardData.getData('Text');//e.clipboardData.getData('text/plain');
                        }
                        if (pastedText.length >= 1) {
                            $clearBtn.show();
                        } else {
                            $clearBtn.hide();
                        }
                    });


                $clearBtn.click(function () {
                    $input.val("");
                    $clearBtn.hide();
                    if (opt.returnFocus === true) {
                        $input.focus();
                    }
                    if (opt.onClear) {
                        if (typeof opt.onClear === "string") {
                            window[opt.onClear] && window[opt.onClear]($input);
                        } else {
                            opt.onClear($input);
                        }
                    }
                    return false;
                });
                $input.data("clear-enable-finish", true);
                return this;
            });
        },
        relistenClear: function () {
            var $o = this;
            return $o.each(function () {
                var $input = $(this);
                if ($input.data("clear-enable-finish") === true) {
                    $input.trigger("keyup");
                    return this;
                } else {
                    return this;
                }
            });
        }

    });
    $(document).ready(function () {
        $("input[data-clear-enable='true']").addClearBtn();
    });

})(jQuery);

 

/**
* @desc    高级查询多条件动态筛选插件,依赖jq,bs
* @author  bear.Tirisfal <571115139#qq.com>
* @since   2018-09-10
********************************/
(function ($, c) {
    /**
     * 构造函数
     * @@param {any} f 当前对象
     * @@param {any} e 传入参数
     */
    var dominate = function (f, e) {
        this.$element = $(f);
        this.options = $.extend({}, $.fn.blmultisr.defaults, e, true);
        this.currentLength = 0;
        this.$searchContainer = this.$element;
        this.$searchContainer.on("click", ".input-wrap a.ads-row-delete", $.proxy(this.deleteSearch, this));
        this.$searchContainer.on("click", ".input-wrap a.ads-row-add", $.proxy(this.addSearch, this));
        this.$searchContainer.on("change", ".field-wrap select", $.proxy(this.fieldChange, this));
        this.valHash = {};
        //初始添加一个
        $.proxy(this.addSearch, this)();
    };
    /**
     * 事件列表
     */
    dominate.prototype = {
        constructor: dominate,
        getTypeInput: function (stype, data) {
            var cutctx = this;
            var $result;
            switch (stype) {
                case "text":
                    $result = $(cutctx.options.inputTmplGroup.input);
                    break;
                case "select":
                    var $select = $(cutctx.options.inputTmplGroup.select);
                    var optionsHtml = [];
                    if (data.opt && data.opt.length)
                        $.each(data.opt,
                            function (j, obj) {
                                optionsHtml.push("<option value='", obj.val, "'>", obj.name, "</option>");
                            });
                    $select.html(optionsHtml.join(""));
                    $result = $select;
                    break;
                default:
                    $result = $(cutctx.options.inputTmplGroup.input);
                    break;
            }
            if (data.register) {
                data.register($result);
            }
            return $result;
        },
        setBtnState: function () {
            var cutctx = this;
            var $addBtns = cutctx.$searchContainer.find(".input-wrap a.ads-row-add");
            var $delBtns = cutctx.$searchContainer.find(".input-wrap a.ads-row-delete");
            if (cutctx.currentLength === 1) {
                $delBtns.hide();
            } else {
                $delBtns.show();
                $addBtns.not(":last").hide();
            }
            $addBtns.last().show();
        },
        addSearch: function () {
            var cutctx = this;
            var $searchItem = $(cutctx.options.adsRowTmpl.replace("{rowclass}", cutctx.options.rowClass));

            //操作符
            var $opSelect = $(cutctx.options.opTmpl);
            var opHtml = [];
            $.each(cutctx.options.opOpt,
                function (i, item) {
                    opHtml.push("<option value='", item.val, "'>", item.name, "</option>");
                });
            $opSelect.html(opHtml.join(""));
            $searchItem.find(".op-wrap").append($opSelect);
            //字段
            var $fieldSelect = $(cutctx.options.fieldTmpl);

            var fieldHtml = [];
            $.each(cutctx.options.fieldOpt,
                function (i, item) {
                    fieldHtml.push("<option value='",
                        item.val,
                        "' data-stype='",
                        item.stype,
                        "'>",
                        item.name,
                        "</option>");
                    cutctx.valHash[item.val] = {};
                    if (item.stype === "select") {
                        cutctx.valHash[item.val].opt = item.options;
                    }
                    cutctx.valHash[item.val].register = item.register;
                });
            $fieldSelect.html(fieldHtml.join(""));
            $searchItem.find(".field-wrap").append($fieldSelect);
            //输入框
            var $inputWrap = $searchItem.find(".input-wrap");
            //var oldstype = $inputWrap.data("stype");
            var stype = $fieldSelect.find("option:selected").data("stype");
            var $valInput = cutctx.getTypeInput(stype, cutctx.valHash[$fieldSelect.val()]);
            $inputWrap.prepend($valInput);
            $inputWrap.data("stype", stype);
            cutctx.$searchContainer.append($searchItem);
            cutctx.currentLength += 1;
            cutctx.setBtnState();
            if (typeof cutctx.options.addCbk === "string")
                cutctx.options.addCbk = window[cutctx.options.addCbk];

            cutctx.options.addCbk && cutctx.options.addCbk(cutctx);
        },
        deleteSearch: function (e) {
            var cutctx = this;
            var $target = $(e.currentTarget);
            $target.closest("." + cutctx.options.rowClass).remove();
            cutctx.currentLength -= 1;
            cutctx.setBtnState();
            if (typeof cutctx.options.delCbk === "string")
                cutctx.options.delCbk = window[cutctx.options.delCbk];

            cutctx.options.delCbk && cutctx.options.delCbk();
        },
        fieldChange: function (e) {
            var cutctx = this;
            var $target = $(e.currentTarget);
            var $inputWrap = $target.closest("." + cutctx.options.rowClass).find(".input-wrap");
            var stype = $target.find("option:selected").data("stype");
            //var oldstype = $inputWrap.data("stype");
            //if (oldstype !== stype) {
            var $valInput = cutctx.getTypeInput(stype, cutctx.valHash[$target.val()]);
            var a = $inputWrap.children("a").detach();
            $inputWrap.html($valInput);
            $inputWrap.append(a);
            $inputWrap.data("stype", stype);
            //}

        },
        getSearchData: function () {
            var result = {};
            this.$searchContainer.find("." + this.options.rowClass).each(function () {
                var $item = $(this);
                var oper = $item.find(".op-wrap select").val();
                var field = $item.find(".field-wrap select").val();
                var value = $item.find(".input-wrap").children().first().val();
                if (!result[oper]) {
                    result[oper] = [{ field: field, val: value }];
                } else {
                    result[oper].push({ field: field, val: value });
                }
            });
            return result;
        }
    };
    /**
     * 初始化
     */
    $.fn.blmultisr = function (e, g) {
        var f;
        var d = this.each(function () {
            var j = $(this);
            var i = j.data("blmultisr");
            var h = typeof e === "object" && e;
            if (!i) {
                j.data("blmultisr", (i = new dominate(this, h)));
            }
            if (typeof e === "string") {
                f = i[e](g);
            }
        });
        return (f === c) ? d : f;
    };
    /**
     * 默认参数
     */
    $.fn.blmultisr.defaults = {
        opOpt: [{ name: "AND", val: "AND" }, { name: "OR", val: "OR" }, { name: "NOT", val: "NOT" }],
        fieldOpt: [],
        rowClass: "ads-row",
        addCbk: null,
        delCbk: null,
        searchCbk: null,
        opTmpl: "<select class='form-control input-sm'></select>",
        fieldTmpl: "<select class='form-control input-sm'></select>",
        inputTmplGroup: {
            input: "<input type='text' size='50' max-length='300' class='form-control input-sm' />",
            select: "<select class='form-control input-sm'></select>"
        },
        adsRowTmpl: "<div class='{rowclass} col-md-12 form-inline'>" +
            "<div class='form-group op-wrap'></div>" +
            "<div class='form-group field-wrap'></div>" +
            "<div class='form-group input-wrap'>" +
            "<a href='javascript:void(0);' class='fa fa-minus-circle text-muted ads-row-delete' title='删除当前筛选' style='display: inline-block;'></a>" +
            "<a href='javascript:void(0);' class='fa fa-plus-circle text-muted ads-row-add' title='添加新的筛选' style='display: inline-block;'></a>" +
            "</div></div>"
    };
    /**
     * 设置构造器
     */
    $.fn.blmultisr.prototype.constructor = dominate;

})(jQuery);

 

 

 

/**
 * @desc    表格中筛选条件的多选下拉,树形下拉 依赖 ztree,注:只能对单个对象进行绑定,返回单个对象的Ztree对象
 * @author  bear.Tirisfal <571115139#qq.com>
 * @since   2018-08-07
********************************/
(function ($) {
    $.fn.extend({
        dropDownTreeSearch: function (option) {
            var opt = {
                elementContainer: ".ui-search-input",
                btnPrefix: "dropdownBtn_",
                dropdownPrefix: "dropdown_",
                treePrefix: "dropdowntree_",
                searchCbk: null,
                subObjKeyVal: null,
                randerCbk: null,
                fixedNodes: {
                    allNode: {
                        //id: index,
                        pId: 0,
                        name: "All",
                        isSingleCheck: true,
                        nocheck: true,
                        realName: "All",
                        dataVal: ""
                    },
                    lineNode: {
                        pId: 0,
                        name: "<span class='split-line'></span>",
                        nocheck: true,
                        chkDisabled: true,
                        realName: "",
                        dataVal: ""
                    },
                    nullNode: {
                        pId: 0,
                        name: "空",
                        nocheck: true,
                        isSingleCheck: true,
                        realName: "空",
                        dataVal: "#"
                    },
                    notNullNode: {
                        pId: 0,
                        name: "非空",
                        nocheck: true,
                        isSingleCheck: true,
                        realName: "非空",
                        dataVal: "*"
                    },
                    customNode: null
                },
                contentNodes: null,
                treeSetting: {
                    view: {
                        dblClickExpand: false,
                        showLine: false, //是否显示节点间的连线
                        showIcon: false,
                        selectedMulti: true,
                        nameIsHTML: true
                    },
                    data: {
                        key: {
                            title: "realName"
                        },
                        simpleData: {
                            enable: true
                        }
                    },
                    callback: {
                        onClick: onClick,
                        onCheck: onCheck
                    },
                    check: {
                        enable: true,
                        chkboxType: { "Y": "s", "N": "s" }
                    }
                },
                btnTemplate: "<a data-val='' id='{dropdownBtnid}'  class='gs-dropdown-select'><span>All</span><i class=' fa fa-caret-down'></i></a>",
                dropDownTemplate: "<div id='{dropdownId}' class='menuContent' style='display:none; position: absolute;'><ul id='{dropdownTreeId}' class='ztree' style='margin-top:0;'></ul></div>",
                canInput: false,
                inputNodeName: ["allNode", "nullNode", "notNullNode"],
                inputBtnTemplate: ["<div class='input-group'>",
                    //"<input type='text' class='form-control' style='z-index:0'>",
                    "<div class='input-group-btn'>",
                    "<a type='button' id='{dropdownBtnid}' class='btn btn-white no-radius'  style='padding:1px 3px;z-index:0'><i class=' fa fa-caret-down'></i></a>",
                    "</div>",
                    "</div>"].join(""),
                seletectTrurnInputTmpl: "<input type='text' searchopermenu='false' name='transcript' id='{nativeId}' clearsearch='false' role='textbox' class='form-control'>"
            };
            opt = $.extend(true, opt, option);
            var $select = $(this);
            var nativeId = $select.attr("id");
            var dropdownBtnid = opt.btnPrefix + nativeId;
            var dropdownId = opt.dropdownPrefix + nativeId.replace2Jquery();
            var dropdownTreeId = opt.treePrefix + nativeId.replace2Jquery();
            var nodes = [];
            var elemOptions = $select.find("option");
            var lastIndex = 1;
            //加载节点数据
            elemOptions.each(function (index, obj) {
                index = index + 1;
                var vals = $(obj).val();
                var text = $(obj).text();
                if (vals == "") {
                    nodes.push(opt.fixedNodes.allNode, opt.fixedNodes.lineNode);
                } else {
                    nodes.push({
                        id: index,
                        pId: 0,
                        name: text,
                        realName: text,
                        dataVal: vals
                    });
                    if (vals.indexOf(",") > -1 && opt.subObjKeyVal) {
                        var subArr = vals.split(",");
                        for (var j = 0; j < subArr.length; j++) {
                            var curKey = text + subArr[j];
                            nodes.push({
                                id: index + j + 919,
                                pId: index,
                                name: subArr[j],
                                realName: subArr[j],
                                dataVal: (opt.subObjKeyVal[curKey] || "")
                            });
                        }
                    }
                }
                lastIndex = index;
            });
            //内容节点
            if (opt.contentNodes && opt.contentNodes.length) {
                if (!nodes.length) nodes.push(opt.fixedNodes.allNode);
                opt.fixedNodes.lineNode && nodes.push(opt.fixedNodes.lineNode);
                for (var m = 0; m < opt.contentNodes.length; m++) {
                    nodes.push({
                        id: lastIndex + m + 1,
                        pId: 0,
                        name: opt.contentNodes[m],
                        realName: opt.contentNodes[m],
                        dataVal: opt.contentNodes[m]
                    });
                }
            }
            if (opt.canInput && !opt.contentNodes) {
                for (var k = 0; k < opt.inputNodeName.length; k++) {
                    if (opt.fixedNodes[opt.inputNodeName[k]])
                        nodes.push(opt.fixedNodes[opt.inputNodeName[k]]);
                }
            } else {
                //添加固定节点
                opt.fixedNodes.lineNode && nodes.push(opt.fixedNodes.lineNode);
                if (opt.fixedNodes.nullNode)
                    nodes.push(opt.fixedNodes.nullNode);
                if (opt.fixedNodes.nullNode)
                    nodes.push(opt.fixedNodes.notNullNode);
            }
            if (opt.fixedNodes.customNode)
                $.each(opt.fixedNodes.customNode, function (i, node) {
                    nodes.push({
                        pId: 0,
                        name: node.name,
                        nocheck: true,
                        isSingleCheck: true,
                        realName: node.realName || node.name,
                        dataVal: node.dataVal
                    });
                });
            //
            var dropDownLiHtml = opt.dropDownTemplate
                .replace("{dropdownId}", dropdownId)
                .replace("{dropdownTreeId}", dropdownTreeId);
            var dropDownBtnHtml = "";

            $("body>#" + dropdownId).remove();
            $("body").append(dropDownLiHtml).html();
            var $container = $select.closest(opt.elementContainer);
            if (opt.canInput) {
                if ($select.is("select")) {
                    $select = $(opt.seletectTrurnInputTmpl.replace("{nativeId}", nativeId));
                }
                dropDownBtnHtml = $(opt.inputBtnTemplate.replace("{dropdownBtnid}", dropdownBtnid));
                dropDownBtnHtml.prepend($select.css("z-index", 0));
            }
            else {
                dropDownBtnHtml = opt.btnTemplate.replace("{dropdownBtnid}", dropdownBtnid);
            }
            $container.html(dropDownBtnHtml);

            var treeObj = $.fn.zTree.init($("#" + dropdownTreeId), opt.treeSetting, nodes);
            //选中
            function onCheck(e, treeId, treeNode) {
                var $dropdownBtn = $("#" + dropdownBtnid.escape2Jquery());
                if (treeNode.isSingleCheck) {
                    treeObj.checkAllNodes(false);
                    //
                    setVal($dropdownBtn, treeNode.dataVal, treeNode.realName);
                    hideMenu($dropdownBtn, $("#" + dropdownId));
                    opt.searchCbk && opt.searchCbk();
                    return;
                }
                var nodes = treeObj.getCheckedNodes(true);
                if (!nodes.length) {
                    setVal($dropdownBtn, "", "All");
                    opt.searchCbk && opt.searchCbk();
                    return;
                }
                if (opt.randerCbk) {
                    opt.randerCbk(treeObj, nodes, treeNode, $dropdownBtn, setVal);
                    opt.searchCbk && opt.searchCbk();
                    return;
                }

                var text = [],
                    values = [];
                nodes.sort(function compare(a, b) { return a.id - b.id; });
                for (var i = 0, l = nodes.length; i < l; i++) {
                    var checkChildState = nodes[i].check_Child_State;
                    if (checkChildState == 1)
                        continue;
                    text.push(nodes[i].realName);
                    values.push(nodes[i].dataVal);
                }
                loadText($dropdownBtn, values, text);
                opt.searchCbk && opt.searchCbk();
            }
            function setVal($btn, val, showName) {
                if (opt.canInput) {
                    if (val == "*") val = "非空";
                    else if (val == "#") val = "空";
                    $btn.closest(opt.elementContainer).find("input[type='text']").val(val);
                } else {
                    $btn.attr("data-val", val).find("span").text(showName);

                }
            }
            //如果超出长度显示个数
            function loadText($btn, values, showtexts) {
                var value = values.join(",");
                var showtext = showtexts.join(",");

                if (!opt.canInput && showtexts.length > 3) {
                    showtext = ["[" + showtexts.length + "]已选择"].join("");
                }
                setVal($btn, value, showtext);
            }
            function onClick(e, treeId, treeNode) {
                treeObj.checkNode(treeNode, !treeNode.checked, true);
                onCheck(e, treeId, treeNode);
            }
            function showMenu($btn, $dropdown) {
                var elRect = $btn[0].getBoundingClientRect();
                var width = elRect.width - 2;
                var height = elRect.height;
                var left = elRect.left;
                if (opt.canInput) {
                    var inputRect = $btn.closest(opt.elementContainer).find("input[type='text']")[0].getBoundingClientRect();
                    left = inputRect.left;
                    $btn.closest(opt.elementContainer).addClass("open");
                    width += inputRect.width;
                }
                $btn.addClass("open");
                $dropdown
                    .css("top", elRect.top + height)
                    .css("left", left)
                    .css("background", "white")
                    .css("min-width", (width < 110 ? 110 : width)).show();

                $("body").bind("mousedown", function (event) { onBodyDown(event, $btn, $dropdown); });
            }
            function hideMenu($btn, $dropdown) {
                $btn.closest(opt.elementContainer).removeClass("open");
                $btn.removeClass("open");
                $dropdown.fadeOut("fast");
                $("body").unbind("mousedown", function (event) { onBodyDown(event, $btn, $dropdown); });
            }
            function onBodyDown(event, $btn, $dropdown) {
                if (!(event.target.id == dropdownBtnid ||
                    event.target.id == dropdownId ||
                    $(event.target).parents("#" + dropdownId).length > 0)) {
                    hideMenu($btn, $dropdown);
                    treeObj.cancelSelectedNode();
                }
            }
            //渲染分割线
            $("#" + dropdownId + " .split-line").closest("li")
                .html("<div class='hr-line-dashed no-margins'></div>")
                .height(1);
            $("#" + dropdownBtnid.escape2Jquery()).click(function () {
                var $this = $(this);
                var $dropdown = $("#" + dropdownId);
                if ($this.hasClass("open")) {
                    hideMenu($this, $dropdown);
                } else {
                    showMenu($this, $dropdown);
                }

            });
            return treeObj;
        }
    });
})(jQuery);

 

posted @ 2018-09-11 17:22  Bear.Tirisfal  阅读(2828)  评论(3编辑  收藏  举报