指定下拉列表的值和标签

时间:2015-06-23 13:10:36

标签: twitter-bootstrap bootstrap-table

我使用data-filter-control="select">启动的下拉列表,其引导表扩展名为wenzhixin(github - filter control extension)。

我使用数据库中的数据填充下拉值,例如&#39; admin&#39;报告&#39;。我想更多地显示标签&#34;用户友好&#34;。这是一个HTML示例:<option value='report'>Report only</option>

问题在于,如果我从我的数据库中提取报告并将其转换为仅报告,则它不会再过滤,因为它正在寻找对于后者在我的数据库而不是第一个。

下拉列表仅包含一个数据,这用于值AND标签,我得到HTML输出:<option value='report'>report</option>

是否可以指定一个值,然后指定要显示的标签?

编辑

截图: enter image description here

enter image description here

1 个答案:

答案 0 :(得分:2)

主页:table.html

//复制每个文件并在本地运行,您将获得所需的输出

     <!DOCTYPE html>
<html>
<head>
   <title>FilterControl</title>
   <meta charset="utf-8">
   <link rel="stylesheet" href="http://issues.wenzhixin.net.cn/bootstrap-table/assets/bootstrap/css/bootstrap.min.css">
   <link rel="stylesheet" href="http://issues.wenzhixin.net.cn/bootstrap-table/assets/bootstrap-table/src/bootstrap-table.css">
   <link rel="stylesheet" href="http://issues.wenzhixin.net.cn/bootstrap-table/assets/examples.css">
   <script src="http://issues.wenzhixin.net.cn/bootstrap-table/assets/jquery.min.js"></script>
   <script src="http://issues.wenzhixin.net.cn/bootstrap-table/assets/bootstrap/js/bootstrap.min.js"></script>
   <script src="http://issues.wenzhixin.net.cn/bootstrap-table/assets/bootstrap-table/src/bootstrap-table.js"></script>
  <!--  <script src="http://issues.wenzhixin.net.cn/bootstrap-table/assets/bootstrap-table/src/extensions/filtercontrol/bootstrap-table-filtercontrol.js"></script> -->
   <script src="filter.js"></script>
</head>
<body>
<div class="container">
   <div class="ribbon">
       <a href="https://github.com/wenzhixin/bootstrap-table-examples/blob/master/extensions/filtercontrol.html" target="_blank">View Source on GitHub</a>
   </div>
   <h1></h1>
   <table id="table"
          data-toggle="table"
          data-url="flare.json"
          data-filter-control="true">
       <thead>
       <tr>
           <th data-field="id">ID</th>
           <th data-field="name" data-filter-control="input">Item Name</th>
           <th data-field="price" data-filter-control="select">Item Price</th>
       </tr>
       </thead>
   </table>
</div>
</body>
</html>

filter.js //修改了filtercontrol.js

/**
 * @author: Dennis Hernández
 * @webSite: http://djhvscf.github.io/Blog
 * @version: v1.0.0
 */

!function ($) {

    'use strict';

    var sprintf = function (str) {
        var args = arguments,
            flag = true,
            i = 1;

        str = str.replace(/%s/g, function () {
            var arg = args[i++];

            if (typeof arg === 'undefined') {
                flag = false;
                return '';
            }
            return arg;
        });
        return flag ? str : '';
    };

    var getFieldIndex = function (columns, field) {
        var index = -1;

        $.each(columns, function (i, column) {
            if (column.field === field) {
                index = i;
                return false;
            }
            return true;
        });
        return index;
    };

    var calculateObjectValue = function (self, name, args, defaultValue) {
        if (typeof name === 'string') {
            // support obj.func1.func2
            var names = name.split('.');

            if (names.length > 1) {
                name = window;
                $.each(names, function (i, f) {
                    name = name[f];
                });
            } else {
                name = window[name];
            }
        }
        if (typeof name === 'object') {
            return name;
        }
        if (typeof name === 'function') {
            return name.apply(self, args);
        }
        return defaultValue;
    };

    $.extend($.fn.bootstrapTable.defaults, {
        filterControl: false,
        onColumnSearch: function (field, text) {
            return false;
        }
    });

    $.extend($.fn.bootstrapTable.COLUMN_DEFAULTS, {
        filterControl: undefined
    });

    $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
        'column-search.bs.table': 'onColumnSearch'
    });

    var BootstrapTable = $.fn.bootstrapTable.Constructor,
        _initHeader = BootstrapTable.prototype.initHeader,
        _initBody = BootstrapTable.prototype.initBody,
        _initSearch = BootstrapTable.prototype.initSearch;

    BootstrapTable.prototype.initHeader = function () {
        _initHeader.apply(this, Array.prototype.slice.apply(arguments));

        if (!this.options.filterControl) {
            return;
        }

        var addedFilterControl = false,
            that = this,
            isVisible,
            html,
            timeoutId = 0;

        $.each(this.options.columns, function (i, column) {
            isVisible = 'hidden';
            html = [];

            if (!column.filterControl) {
                html.push('<div style="height: 34px;"></div>');
            } else {
                html.push('<div style="margin: 0px 2px 2px 2px;" class="filterControl">');

                if (column.filterControl && column.searchable) {
                    addedFilterControl = true;
                    isVisible = 'visible'
                }
                switch (column.filterControl.toLowerCase()) {
                    case 'input' :
                        html.push(sprintf('<input type="text" class="form-control" style="width: 100%; visibility: %s">', isVisible));
                        break;
                    case 'select':
                        html.push(sprintf('<select class="%s form-control" style="width: 100%; visibility: %s"></select>',
                            column.field, isVisible))
                        break;
                }
            }

            that.$header.find(sprintf('.th-inner:contains("%s")', column.title)).next().append(html.join(''));
        });

        if (addedFilterControl) {
            this.$header.off('keyup', 'input').on('keyup', 'input', function (event) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(function () {
                    that.onColumnSearch(event);
                }, that.options.searchTimeOut);
            });

            this.$header.off('change', 'select').on('change', 'select', function (event) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(function () {
                    that.onColumnSearch(event);
                }, that.options.searchTimeOut);
            });
        } else {
            this.$header.find('.filterControl').hide();
        }
    };

    BootstrapTable.prototype.initBody = function () {
        _initBody.apply(this, Array.prototype.slice.apply(arguments));

        var that = this,
            data = this.getData();

        for (var i = this.pageFrom - 1; i < this.pageTo; i++) {
            var key,
                item = data[i];
            var txt=item['text'];//changes added here to show different text on option
            console.log(txt);
            $.each(this.header.fields, function (j, field) {

                var value = item[field],
                    column = that.options.columns[getFieldIndex(that.options.columns, field)];

                value = calculateObjectValue(that.header,
                    that.header.formatters[j], [value, item, i], value);

                if ((!column.checkbox) || (!column.radio)) {
                    if (column.filterControl !== undefined && column.filterControl.toLowerCase() === 'select'
                        && column.searchable) {

                        var selectControl = $('.' + column.field),
                            iOpt = 0,
                            exitsOpt = false,
                            options;
                        if (selectControl !== undefined) {
                            options = selectControl.get(0).options;

                            if (options.length === 0) {

                                //Added the default option
                                selectControl.append($("<option></option>")
                                    .attr("value", '')
                                    .text(''));

                                selectControl.append($("<option></option>")
                                    .attr("value", value)
                                    .text(txt));
                            } else {
                                for (; iOpt < options.length; iOpt++) {
                                    if (options[iOpt].value === value) {
                                        exitsOpt = true;
                                        break;
                                    }
                                }

                                if (!exitsOpt) {
                                    selectControl.append($("<option></option>")
                                        .attr("value", value)
                                        .text(txt));

                                }
                            }
                        }
                    }
                }
            });
        }
    };

    BootstrapTable.prototype.initSearch = function () {
        _initSearch.apply(this, Array.prototype.slice.apply(arguments));

        var that = this;
        var fp = $.isEmptyObject(this.filterColumnsPartial) ? null : this.filterColumnsPartial;

        //Check partial column filter
        this.data = fp ? $.grep(this.data, function (item, i) {
            for (var key in fp) {
                var fval = fp[key].toLowerCase();
                var value = item[key];
                value = calculateObjectValue(that.header,
                    that.header.formatters[$.inArray(key, that.header.fields)],
                    [value, item, i], value);

                if (!($.inArray(key, that.header.fields) !== -1 &&
                    (typeof value === 'string' || typeof value === 'number') &&
                    (value + '').toLowerCase().indexOf(fval) !== -1)) {
                    return false;
                }
            }
            return true;
        }) : this.data;
    };

    BootstrapTable.prototype.onColumnSearch = function (event) {
        var text = $.trim($(event.currentTarget).val());
        var $field = $(event.currentTarget).parent().parent().parent().data('field')

        if ($.isEmptyObject(this.filterColumnsPartial)) {
            this.filterColumnsPartial = {};
        }
        if (text) {
            this.filterColumnsPartial[$field] = text;
        } else {
            delete this.filterColumnsPartial[$field];
        }

        this.options.pageNumber = 1;
        this.onSearch(event);
        this.updatePagination();
        this.trigger('column-search', $field, text);
    };
}(jQuery);

<强> flare.json

[
   {
       "id": 0,
       "name": "Item 0",
       "price": "$0",
       "text": "Zero"
   },
   {
       "id": 1,
       "name": "Item 1",
       "price": "$1",
       "text": "One"
   },
   {
       "id": 2,
       "name": "Item 2",
       "price": "$2",
        "text": "Two"
   },
   {
       "id": 3,
       "name": "Item 3",
       "price": "$3",
        "text": "Three"
   },
   {
       "id": 4,
       "name": "Item 4",
       "price": "$4",
        "text": "Four"
   }

]