Jquery Datatables Date Range Filter

后端 未结 3 1374
心在旅途
心在旅途 2021-01-15 16:42

The code below is working perfectly but I need to add a new functionality to allow the user to filter on a range of records based on their start date and end date, the user

3条回答
  •  甜味超标
    2021-01-15 17:29

    I don't know if helps but i do the thing you ask like this

    EDIT

    Here more explanation. The $.fn.DataTable.ext.search it's the API provided for Datatables to extend the functions of filtering. First there is an array wich has the names of the tables who has to apply the function below (this is in case there is more than one table on the same page), then gets the value from de datepickers and split for create another Date who has the same format in the three cases (From, To and StartDate). Then compares that dates between them and filter as appropiate. The StartDate is from the current record of the Table.

    At the datepickers i added the class date-range-filter

    var allowFilter = ['tableOT'];
    
    $('.date-range-filter').change(function() {
                oTable.draw();
            });
    
    $.fn.dataTable.ext.search.push(
          function(settings, data, dataIndex) {
              // check if current table is part of the allow list
              if ( $.inArray( settings.nTable.getAttribute('id'), allowFilter ) == -1 )
              {
                  // if not table should be ignored
                  return true;
              }
              var min = $("#<%=txtFechaDesde.ClientID %>").val();
              var max = $("#<%=txtFechaHasta.ClientID %>").val();
              var fromDate;
              var toDate;
              // need to change str order before making  date obect since it uses a new Date("mm/dd/yyyy") format for short date.
              var d = data[0].split("/");
              var startDate = new Date(d[1]+ "/" +  d[0] +"/" + d[2]);
              if(min != ""){
                  var fd = min.split("/");
                  fromDate =  new Date(fd[1]+ "/" +  fd[0] +"/" + fd[2]);
              }
              if(max != ""){
                  var td = max.split("/");
                  toDate =  new Date(td[1]+ "/" +  td[0] +"/" + td[2]);
              }
    
              if (fromDate == null && toDate == null) { return true; }
              if (fromDate == null && startDate <= toDate) { return true;}
              if(toDate == null && startDate >= fromDate) {return true;}
              if (startDate <= toDate && startDate >= fromDate) { return true; }
              return false;
          }
        );
    

提交回复
热议问题