【问题标题】:How to add a dropdownlist next to the filter box with Jquery datatables?如何在带有 Jquery 数据表的过滤器框旁边添加一个下拉列表?
【发布时间】:2014-04-22 17:53:45
【问题描述】:

我正在对我的 asp.net 页面上的所有网格使用 Jquery 数据表 (http://datatables.net/)。启用 bFilter 后,将显示搜索过滤器。我想在它旁边添加一个下拉列表(选择要应用过滤器的特定列)?如何添加此 html 并将下拉列表值传递给我的下一页,如“sSearch”使用:

<select>
  <option value="column1">column1/option>
  <option value="column2">column2</option>
  <option value="column3">column3</option>
</select>

【问题讨论】:

    标签: jquery asp.net jquery-datatables


    【解决方案1】:

    以下是使用名为fnCreateFilterColumnSelector 的函数扩展数据表的示例。此函数将在所有搜索框旁边添加 &lt;select&gt; 元素,用可用列填充它们,并处理 select.change 事件以确保数据表仅按该列过滤。

    这个 javascript 代码只需要在你的 datatables.js 之后加载。然后,在初始化.dataTable(); 之后,调用fnCreateFilterColumnSelector 函数。

    示例

    $(document).ready(function () {
        var dt = $('table.display').dataTable();
        dt.fnCreateFilterColumnSelector();
    });
    

    数据表扩展代码

    (function ($, window, document) {
        $.fn.dataTableExt.oApi.fnCreateFilterColumnSelector = function (oSettings) {
            var filterColumnSelectElement;
            $(oSettings.aanFeatures.f).each(function (index, filterDiv) {
                filterDiv = $(filterDiv);
                // see if we have a select here or not yet
                if (filterDiv.find(".dataTables_filterColumnSelect").length == 0) {
                    // nope, so add one ... see if we have build the select yet
                    if (filterColumnSelectElement === undefined) {
                        // the select hasn't been built yet, build it now
                        filterColumnSelectElement = $("<select></select>").addClass("dataTables_filterColumnSelect").css({ width: "120px", marginLeft: "10px" });
                        // add the all option
                        $("<option>*all</option>").val("all").appendTo(filterColumnSelectElement);
                        // add our bSearchable columns
                        $(oSettings.aoColumns).each(function (index, column) {
                            // see if this is a searchable column
                            if (column.bSearchable) {
                                // it is, add it (be sure to trim and remove \n chars
                                $("<option></option>").text(column.sTitle.replace(/\n/g, "").trim()).val(index).appendTo(filterColumnSelectElement);
                            }
                        });
                        // bind change event to select
                        filterColumnSelectElement.change(function () {
                            var theSelect = $(this);
                            // change all other elements to the same value
                            $(oSettings.aanFeatures.f).each(function (index, filterDiv) {
                                $(filterDiv).find(".dataTables_filterColumnSelect").val(theSelect.val());
                            });
                            // instead of overriding what the input does with our on code, we just just toggle the "bSearchable" values of our
                            // columns when we want to target an individual column ...
                            // see if we are going to search all
                            if (theSelect.val() === "all") {
                                // change all our columns back to searchable
                                $(theSelect.find("option")).each(function (i, theOption) {
                                    // make sure the option has a number as a val
                                    var columnIndex = parseInt($(theOption).val());
                                    if (!isNaN(columnIndex)) {
                                        // switch it back to bSearchable
                                        oSettings.aoColumns[columnIndex].bSearchable = true;
                                    }
                                });
                            }
                            else {
                                // change all the columns to not searchable
                                $(oSettings.aoColumns).each(function (i, column) {
                                    column.bSearchable = false;
                                });
                                // change our selected colum to b searchable
                                oSettings.aoColumns[parseInt(theSelect.val())].bSearchable = true;
                            }
                            // kick off a search again ... need to clear out the last search to get it to do anything
                            oSettings.oPreviousSearch.sSearch = "dummySearch";
                            $(theSelect).closest("div").find("input").trigger("keyup.DT");
                        });
                    }
                    // append a clone of our select element
                    filterDiv.append(filterColumnSelectElement.clone(true));
                    // increase the width of the div to fit the select
                    filterDiv.css("width", (filterDiv.width() + filterColumnSelectElement.width() + 10).toString() + "px");
                }
            });
        }
    })(jQuery, window, document);
    

    【讨论】:

    • 感谢您提供此示例!
    【解决方案2】:

    这略有不同,但让我们将这些过滤器选项放在您要过滤的列旁边。示例取自 datatable's site。去那里看看它最终的样子。

    (function($) {
    /*
     * Function: fnGetColumnData
     * Purpose:  Return an array of table values from a particular column.
     * Returns:  array string: 1d data array 
     * Inputs:   object:oSettings - dataTable settings object. This is always the last argument past to the function
     *           int:iColumn - the id of the column to extract the data from
     *           bool:bUnique - optional - if set to false duplicated values are not filtered out
     *           bool:bFiltered - optional - if set to false all the table data is used (not only the filtered)
     *           bool:bIgnoreEmpty - optional - if set to false empty values are not filtered from the result array
     * Author:   Benedikt Forchhammer <b.forchhammer /AT\ mind2.de>
     */
    $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
        // check that we have a column id
        if ( typeof iColumn == "undefined" ) return new Array();
    
        // by default we only want unique data
        if ( typeof bUnique == "undefined" ) bUnique = true;
    
        // by default we do want to only look at filtered data
        if ( typeof bFiltered == "undefined" ) bFiltered = true;
    
        // by default we do not want to include empty values
        if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
    
        // list of rows which we're going to loop through
        var aiRows;
    
        // use only filtered rows
        if (bFiltered == true) aiRows = oSettings.aiDisplay; 
        // use all rows
        else aiRows = oSettings.aiDisplayMaster; // all row numbers
    
        // set up data array    
        var asResultData = new Array();
    
        for (var i=0,c=aiRows.length; i<c; i++) {
            iRow = aiRows[i];
            var aData = this.fnGetData(iRow);
            var sValue = aData[iColumn];
    
            // ignore empty values?
            if (bIgnoreEmpty == true && sValue.length == 0) continue;
    
            // ignore unique values?
            else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
    
            // else push the value onto the result data array
            else asResultData.push(sValue);
        }
    
        return asResultData;
    }}(jQuery));
    
    
    function fnCreateSelect( aData )
    {
        var r='<select><option value=""></option>', i, iLen=aData.length;
        for ( i=0 ; i<iLen ; i++ )
        {
            r += '<option value="'+aData[i]+'">'+aData[i]+'</option>';
        }
        return r+'</select>';
    }
    
    
    $(document).ready(function() {
        /* Initialise the DataTable */
        var oTable = $('#example').dataTable( {
            "oLanguage": {
                "sSearch": "Search all columns:"
            }
        } );
    
        /* Add a select menu for each TH element in the table footer */
        $("tfoot th").each( function ( i ) {
            this.innerHTML = fnCreateSelect( oTable.fnGetColumnData(i) );
            $('select', this).change( function () {
                oTable.fnFilter( $(this).val(), i );
            } );
        } );
    } );
    

    【讨论】:

    • 谢谢你给我这个例子!
    猜你喜欢
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-19
    • 2022-01-16
    • 2023-03-21
    • 2012-03-25
    相关资源
    最近更新 更多