Specify value and label of dropdown

2k views Asked by At

I use a dropdown initiated with data-filter-control="select"> with a bootstrap table extension of wenzhixin (github - filter control extension).

I fill the dropdown values with data from a database, such as 'admin', 'report'. I would like to display a label more "user-friendly". Here's a HTML example: <option value='report'>Report only</option>.

The issue is that if I fetch report from my database and convert it to Report only, it doesn't filter anymore because it's looking for the latter in my database instead of the first.

The dropdown takes only one data and this is used for value AND label, I get that HTML ouput: <option value='report'>report</option>.

Is it possible to specify a value then a label to display?

EDIT

Screenshots: enter image description here

enter image description here

1

There are 1 answers

0
praveen On BEST ANSWER

Main page:table.html

// copy each file and run in your local, you will get the desired output

     <!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// modified 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"
   }

]