jquerysharepointdatatablesharepoint-listsharepoint-rest-api

jQuery Datatable Sharepoint list filter data by clicking on icons/badges


I have this code:

    <div class="container">
    <div class="card-deck">
      <div class="card t1" >
        <div class="card-header" id="Not-Started" style="width:100%">0</div>
        <div class="card-body">
          <h5 class="card-title"><i class="fa fa-ban"></i> Not-Started</h5>
        </div>
      </div>
    
      <div class="card t2" style="width:400px">
      <div class="card-header" id="In_process" style="width:100%">0</div>
        <div class="card-body">
          <h5 class="card-title"><i class="fa fa-clock-o"></i> In process</h5>
        </div>
      </div>
      
        <div class="card t3" >
        <div class="card-header" id="Late" style="width:100%">0</div>
        <div class="card-body">
          <h5 class="card-title"><i class="fa fa-pause-circle-o"></i> Late</h5>
        </div>
      </div>

         <div class="card t5" >
        <div class="card-header" id="Closed" style="width:100%">0</div>
        <div class="card-body">
          <h5 class="card-title"><i class="fa fa-close"></i> Closed</h5>
        </div>
      </div>

    </div>

    </div>

    <div class="row ms-5 pt-5 pb-5">
       <div class="col-12">
            <div class="row">
                  <div class="col-1 text-center">
                    <a style="cursor: pointer;"> 
                        <i data-toggle='tooltip' data-placement='top' data-filter="Workplace Services" title='Workplace Services' class='dtFilter fas fa-laptop-house' style='color:#0080cc;font-size:48px' ></i>
                        <div class="mt-3 pb-3">Workplace</div>
                          </a>
                </div>
                <div class="col-1 text-center">
                  <a style="cursor: pointer;"> 
                      <i data-toggle='tooltip' data-placement='top' data-filter="Application Services" title='Application Services' class='dtFilter fas fa-table' style='color:#0080cc;font-size:48px' ></i>
                      <div class="mt-3 pb-3">Application</div>
                  </a>
                </div>
                <div class="col-1 text-center">
                  <a style="cursor: pointer;"> 
                      <i data-toggle='tooltip' data-placement='top' data-filter="Subject Matter Expertise Service" title='Subject Matter Expertise Services' class='dtFilter fas fa-sign' style='color:#0080cc;font-size:48px' ></i>
                      <div class="mt-3 pb-3">Subject Matter Expertise</div>
                    </a>
                </div>
                <div class="col-1 text-center">
                  <a style="cursor: pointer;"> 
                      <i data-toggle='tooltip' data-placement='top'  data-filter="Logistics Support Services"  title='Logistic Support Services' class='dtFilter fas fa-shipping-fast' style='color:#0080cc;font-size:48px' ></i>
                      <div class="mt-3 pb-3">Logistic</div>
                    </a>
                </div>
                <div class="col-1 text-center">
                  <a style="cursor: pointer;"> 
                      <i data-toggle='tooltip' data-placement='top' data-filter="Infrastructure Services" title='Infrastructure Services' class='dtFilter fas fa-network-wired' style='color:#0080cc;font-size:48px' ></i>
                      <div class="mt-3 pb-3">Infrastructure</div>
                    </a>
                </div>
                <div class="col-1 text-center">
                  <a style="cursor: pointer;"> 
                    <i data-toggle='tooltip' data-placement='top' data-filter="Platform Services" title='Platform Services' class='dtFilter fas fa-globe' style='color:#0080cc;font-size:48px' ></i>
                    <div class="mt-3 pb-3">Platform</div>
                  </a>
                </div>
                <div class="col-1 text-center">
                  <a style="cursor: pointer;"> 
                      <i data-toggle='tooltip' data-placement='top' data-filter="Security Services" title='Security Services' class='dtFilter fas fa-lock' style='color:#0080cc;font-size:48px' ></i>
                      <div class="mt-3 pb-3">Security</div>
                    </a>
                </div>
                <div class="col-1 text-center">
                  <a style="cursor: pointer;">  
                      <i data-toggle='tooltip' data-placement='top' data-filter="Training Services" title='Training Services' class='dtFilter fas fa-user-graduate' style='color:#0080cc;font-size:48px' ></i>
                      <div class="mt-3 pb-3">Training</div>
                    </a>
        </div>
        <div class="col-1 text-center">
          <a style="cursor: pointer;">  
              <i data-toggle='tooltip' data-placement='top' data-filter="Other Services" title='Other Services' class='dtFilter fas fa-ellipsis-h' style='color:#0080cc;font-size:48px' ></i>
              <div class="mt-3 pb-3">Other</div>
            </a>
        </div>
          </div>
       </div>
       <div class="col-row">
        <div class="col">

        </div>
       </div>

     </div>
     <button class="btn btn-link btn-clear-filters" style="cursor: pointer; text-decoration: none; color:#0080cc ;" type="button" >
      Clear Filters
     </button></div><div class="ms-clear"></div>
    <br>

    <div class="row">
        <div class="col-md-12">
        <div class="table-responsive">
            <table id="pDashboard" class="table display" cellspacing="0" style="width:100% !important;">
                <thead>  
                    <tr>
                        <th></th>
                        <th>ID</th> 
                        <th>Name</th> 
                        <th>Status</th> 
                        <th>Project Owner</th>
                        <th>Project Sponsor</th>
                    </tr>  
                </thead>  
                <tfoot> </tfoot>  
            </table>
        </div>        
       </div>
       </div>


    <script>
    $(document).ready(function() {
    loadListItems(); //to load list items
    getCount('Not-Started');
    getCount('In_process');
    getCount('Late');
    getCount('Closed');

    $('.card-header').each(function() {
            $(this).prop('Counter', 0).animate({
                    Counter: $(this).text()
            }, {
                    duration: 1500,
                    easing: 'swing',
                    step: function(now) {
                            $(this).text(Math.ceil(now));
                    }
            });
    })


    });

    //click event for toggle
    function addClickEvent() {
    }

    function loadListItems() {
    var oDataUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('ProjectDetails')/items?$select=ID,StartDate,EndDate,Title,Status,Description,Project_x0020_Summary,Project_x0020_Summary,EstimatedCost,StartDate,EndDate,ProjectManager/Title,Project_x0020_Sponsor/Title&$expand=ProjectManager,Project_x0020_Sponsor";
    console.log(_spPageContextInfo);
    $.ajax({
            url: oDataUrl,
            type: "GET",
            dataType: "json",
            headers: {
                    "accept": "application/json;odata=verbose"
            },
            success: successFunction,
            error: errorFunction
    });
    }


    function getCount(status) {
    //console.log(category);
    var listName = "ProjectDetails";
    var query = "$filter=(Status eq '" + status + "')";
    var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?" + query;

    getListItems(url, function(data) {
            var items = data.d.results;
            $('#' + status).text(items.length);
    });

    }



    function successFunction(data) {
    try {
            var dataTableExample = $('#pDashboard').DataTable();
            if (dataTableExample != 'undefined') {
                    dataTableExample.destroy();
            }

            dataTableExample = $('#pDashboard').DataTable({
            fixedHeader: true,
                    //scrollY: "350px",
                    autoWidth: true,
                    dom: 'Blfrtip',
                    "pageLength": 15,
                    buttons: [
    {
        extend: 'excelHtml5',
        text: 'Excel',
        customize: function( xlsx ) {
            var sheet = xlsx.xl.worksheets['page.xml'];
            $('row:first c', sheet).attr( 's', '42' );
        }
    }
        ],
                    /* order: [
                  [0, 'desc'],
  
                 ],*/
                 order: [[1, 'asc']],
                    columnDefs: [{
                                    "width": "3%",
                                    "targets": [0]
                            }, {
                                    "width": "3%",
                                    "targets": [1]
                            }, {
                                    "width": "20%",
                                    "targets": [2]
                            }, {
                                    "width": "6%",
                                    "targets": [3]
                            }, {
                                    "width": "10%",
                                    "targets": [4]
                            }, {
                                    "width": "10%",
                                    "targets": [5]
                            }

                    ],

                    "aaData": data.d.results,
                    "aoColumns": [{
                            "className": 'details-control',
                            "orderable": false,
                            "data": null,
                            "defaultContent": ''
                    }, {
                            "mData": "ID",
                            "render": function(mData, type, row, meta) {
                                    var returnText = "";
                                    var url = _spPageContextInfo.webAbsoluteUrl + "/Lists/ProjectDetails/DispForm.aspx?ID=" + mData;
                                    returnText = "<a target='_blank' href=" + url + ">" + mData + "</a>";
                                    return returnText;
                            }

                    }, {
                            "mData": "Title"

                    }, {
                            "mData": "Status",
                            "render": function(data) {

                                    if (data === null) return "";
                                    else
                                            return "<label class='badge1 badge-" + data + "'>" + data + "</label>"
                            }
                    }, {
                            "mData": "ProjectManager",
                            "render": function(mData, type, full, meta) {
                                    var returnText = "";
                                    if (mData.Title == undefined) return "";
                                    else return mData.Title;
                                    console.log(mData.Title);
                            }
                    }, {
                            "mData": "Project_x0020_Sponsor",
                            "render": function(mData, type, full, meta) {
                                    var returnText = "";
                                    if (mData.Title == undefined) return "";
                                    else return mData.Title;
                                    console.log(mData.Title);
                            }
                    }],
                            rowGroup: {
        dataSrc: 2
    },


            });


            $('#pDashboard tbody').on('click', 'td.details-control', function() {
                    //alert('H');
                    var tr = $(this).closest('tr');
                    var row = dataTableExample.row(tr);

                    if (row.child.isShown()) {
                            // This row is already open - close it
                            row.child.hide();
                            tr.removeClass('shown');
                    } else {
                            // Open this row
                            row.child(format(row.data())).show();
                            tr.addClass('shown');
                    }
            });
            
            dataTableExample
    .columns()
    .flatten()
    .unique()
    .each(function (colID) {

        // Create the select list in the
        // header column header
        // On change of the list values,
        // perform search operation
        var mySelectList = $('<select><option value=""></option></select>')
        .appendTo(dataTableExample.column(colID).header())
        .on("change", function () {
            dataTableExample.column(colID).search($(this).val());

            // update the changes using draw() method
            dataTableExample.column(colID).draw();
        });

        // Get the search cached data for the
        // first column add to the select list
        // using append() method
        // sort the data to display to user
        // all steps are done for EACH column
        dataTableExample
        .column(colID)
        .cache("search")
        .sort()
        .unique()
        .each(function (param) {
            mySelectList.append(
            $('<option value="' + param + '">'
                + param + "</option>")
            );
        });
            });


            function format(d) {
                    // `d` is the original data object for the row
                    return '<table cellpadding="5" cellspacing="0" style="margin-left:-12px;width:100%;" border="0">' +
                            '<tr>' +
                            '<td><b>Description:</b></td>' +
                            '<td>' + d.Description + '</td>' +
                            '</tr>' +
                            '<tr>' +
                            '<td><b>Project type:</b></td>' +
                            '<td>' + d.Project_x0020_Summary + '</td>' +
                            '</tr>' +
                            '<tr>' +
                            '<td colspan="2"><table style="width: 101%;">' +
                            '<td><b>Start Date:</b></td>' +
                            '<td>' + getDates(d.StartDate) + '</td>' +
                            '<td><b>End Date:</b></td>' +
                            '<td>' + getDates(d.EndDate) + '</td>' +
                            '</td></table>'
                    '</tr>' +

                    '</table>';
            }
            
            //


            } catch (e) {
            //alert(e.message);  
            }
    }




    function errorFunction(data, errCode, errMessage) {
    Console.log("Error: " + errMessage);
    }



    function numberFormat(data) {
    var s = (data + ""),
            a = s.split(""),
            out = "",
            iLen = s.length;

    for (var i = 0; i < iLen; i++) {
            if (i % 3 === 0 && i !== 0) {
                    out = ',' + out;
            }
            out = a[iLen - i - 1] + out;
    }
    return out;
    }


    function getListItems(siteurl, success, failure) {
    $.ajax({
            url: siteurl,
            method: "GET",
            async: false,
            headers: {
                    "Accept": "application/json; odata=verbose"
            },
            success: function(data) {
                    success(data);
            },
            error: function(data) {
                    failure(data);
            }
    });
    }

    function getDates(data) {
    var retDate = "";
    if (data != null) {
            var date = new Date(data);
            var month = date.getMonth() + 1;
            //return (month.length > 1 ? month : "0" + month) + "/" + date.getDate() + "/" + date.getFullYear();
            retDate = formatDate(date);
    }
    return retDate;

    }

    function formatDate(date) {
    //var today = new Date();
    var dd = date.getDate();
    var mm = date.getMonth() + 1; //January is 0!

    var yyyy = date.getFullYear();
    if (dd < 10) {
            dd = '0' + dd;
    }
    if (mm < 10) {
            mm = '0' + mm;
            }        
            var formatedDate = yyyy + '-' + mm + '-' + dd;
    
            return formatedDate;
    }
    
    
    </script>

Result:

etc

The problem is I don't know how to achieve filtering this table by clicking on an icon. For example, I want to click on "Workplace" icon and that table would show only items with project type (field name Project_x0020_Summary) "Workplace Services" and so on. Also I want click on "Late" badge and get table filtered by status "Late".

There is "data-filter" attribute to use for filtering table data, for example

        <td data-filter="Tiger Nixon">T. Nixon</td>

but how to use it with Sharepoint list and how to achieve filtering by clicking on icon/badge?

Thanks in advance!


Solution

  • As @andrewJames mentioned, solution is quite simple:

    For icon:

    <div class="col-1 text-center">
      <a style="cursor: pointer;"> 
        <i data-toggle='tooltip' data-placement='top' data-filter="Workplace Services" title='Workplace Services' class='dtFilter fas fa-bomb' style='color:#0084b6;font-size:48px' ></i>
        <div class="mt-3 pb-3">Workplace</div>
      </a>
    </div>
    

    I use this function to filter by "data-filter" value in column "Project_x0020_Summary":

    $('i').on('click', function() {
      var searchTerm = $(this).attr('data-filter');
      dataTableExample.column(6).search(searchTerm);
      dataTableExample.column(6).draw();
    });
    

    But first I had to add this column to the table

    "mData": "Project_x0020_Summary"
    

    And then hide it with

    dataTableExample.column(6).visible(false);
    

    It's more like a workaround, but it works for me.