searching a jquery datatables

霸气de小男生 提交于 2021-02-20 02:57:26

问题


I am using jquery datatables 1.10 and trying to search and filter a table. I would like to use a search text box that searches two columns and a check box to filter the results of a third column. Here is my datatable:

var url = '@Url.Action("SupportClass1Search", "SupportClass1")';
$('#SupportClass1DataTable').DataTable({
    "serverSide": true,
    "processing": true,
    "ajax": url,
    "ordering": true,
    "dom": '<"top"prl<"clear">>t<"bottom">pi<"clear">',
    "pageLength": 10,
    "autoWidth": false,
    "columns": [
        { // create a link column using the value of the column as the link text
            "data": "SupportClass1Id",
            "width": "20%",
            "render": function (oObj) { return "<a href='#' onclick='editItem(\"" + oObj + "\")'>" + oObj + "</a>"; },
        },
        { "data": "SupportClass1Name", "sWidth": "70%" },
        { // convert boolean values to Yes/No
            "data": "Active",
            "width": "7%",
            "render": function (data, type, full) {
                if (data == true)
                { return 'Yes'; }
                else
                { return 'No'; }
            }
        }
    ]
})

I want to filter the 3rd column (Active) based on a checkbox value. The JS below works to filter the table but is not picking up the Active column when I enter "Yes" or "No":

// use an outside search input
oTable = $('#SupportClass1DataTable').DataTable();

$('#btnSearch').click(function () {
    oTable.search($('#txtSearch').val()).draw();
})

Also, I would prefer to search the Active column separately, kind of like this:

oTable
    .column(2).search('Yes')
    .columns([0,1]).search($('#txtSearch').val())
    .draw();

but this doesn't work. Any help is appreciated


回答1:


You may want to use the columnfilter plugin http://jquery-datatables-column-filter.googlecode.com/svn/trunk/index.html ( a jQuery Datatables plugin) as it can do much of what you are seeking. Here is an example in jsFiddle Demo here. In this example I am using 2 fields for text filtering and the 3rd is a dropdown

    oTable = $("#myTable").dataTable({
    bInfo: false,
    bSort: false,
    bSortable: false,
        "data": arrayData,
        "columns": [{
        "data": "Emp"
    }, {
        "data": "Name"
    }, {
        "data": "Role"
    }, {
        "data": "Notes"
    }]
}).columnFilter({
    sPlaceHolder : "head:before",
    aoColumns : [{
        type : "text"
    }, {
        type : "text"
    }, {
        type : "select",
        values : arrayRoles
    }]
});



回答2:


I figured it out. Using version 1.10 you have to use ajax.data:

https://datatables.net/reference/option/ajax.data

In my initialization, I used the following to add an extra parameter to my ajax call:

"ajax": {
    "url": url,
    "data": function (d) {
        d.activeOnly = $('#activeOnly').is(':checked');
    }
},

Here is my full initialization:

$(document).ready(function () {
    // initialize the data table
    var url = '@Url.Action("SupportClass1Search", "SupportClass1")';
    $('#SupportClass1DataTable').DataTable({
        "serverSide": true,
        "processing": true,
        "ajax": url,
        "ordering": true,
        "dom": '<"top"prl<"clear">>t<"bottom">pi<"clear">',
        "pageLength": 10,
        "autoWidth": false,
        "ajax": {
            "url": url,
            "data": function (d) {
                d.activeOnly = $('#activeOnly').is(':checked');
            }
        },
        "columns": [
            { // create a link column using the value of the column as the link text
                "data": "SupportClass1Id",
                "width": "20%",
                "render": function (oObj) { return "<a href='#' onclick='editItem(\"" + oObj + "\")'>" + oObj + "</a>"; },
            },
            { "data": "SupportClass1Name", "sWidth": "70%" },
            { // convert boolean values to Yes/No
                "data": "Active",
                "width": "7%",
                "render": function (data, type, full) {
                    if (data == true)
                    { return 'Yes'; }
                    else
                    { return 'No'; }
                }
            }
        ]
    })

    oTable = $('#SupportClass1DataTable').DataTable();

    // this is a checkbox outside the datatable 
    // whose value I wanted to pass back to my controller

    $('#activeOnly').click(function () {
        oTable.search($('#txtSearch').val()).draw();
    })

    $('#btnSearch').click(function () {
        oTable.search($('#txtSearch').val()).draw();
    })
});

I am using a class as a model for the DataTable. I added the activeOnly parameter/property here also:

/// <summary>
/// this class provides a model to use with JQuery DataTables plugin
/// </summary>
public class jQueryDataTableParamModel
{
    #region DataTable specific properties
    /// <summary>
    /// Request sequence number sent by DataTable,
    /// same value must be returned in response
    /// </summary>       
    public string draw { get; set; }

    /// <summary>
    /// Number of records that should be shown in table
    /// </summary>
    public int length { get; set; }

    /// <summary>
    /// First record that should be shown(used for paging)
    /// </summary>
    public int start { get; set; }
    #endregion

    #region Custom properties

    public bool activeOnly { get; set; }

    #endregion
}

This is my controller:

public ActionResult SupportClass1Search(jQueryDataTableParamModel param)
{
    // initialize the datatable from the HTTP request
    var searchString = Request["search[value]"];
    var sortColumnIndex = Convert.ToInt32(Request["order[0][column]"]);
    var sortDirection = Request["order[0][dir]"]; // asc or desc

    // query the database and output to a viewmodel
    var lvm = new SupportClass1SearchViewModel { };
    if (String.IsNullOrEmpty(searchString))
    {
        lvm.SupportClass1List = supportClass1Service.GetAll();
    }
    else
    {
        lvm.SupportClass1List = supportClass1Service.FindBy(t => (t.SupportClass1Name.Contains(searchString))
            && (t.Active.Equals(param.activeOnly) || param.activeOnly == false));
    }

    // do a bunch of stuff and retunr a json string of the data
    return MyJson;
}

Now, when I click on the activeOnly checkbox and it redraws the table passing true or false to the controller.



来源:https://stackoverflow.com/questions/25585602/searching-a-jquery-datatables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!