How do I make a date filter load the data (at runtime) according to what the user is typing?

1

I have the screen below and as soon as the user is typing the date, the function is already loading the data.

I do not know which jQuery event to use and / or if it is something more detailed.

    
asked by anonymous 26.03.2018 / 21:54

1 answer

1

You can go by calling the function that will do the filter using the input event (as you type in the fields):

$(elementos).on("input"...

In the example below, when the "start date" and "end date" fields both have 10 characters (which corresponds to the format dd / MM / yyyy), it will fire the .each that will look in each column td:eq(1) os 10 first characters ( .substring(0,10) ) of the text of the second td ( :eq(1) ) that is referring to the date and compare if it is contained in the range of dates of inputs . If it is, it will keep its line visible ( $(this).closest("tr").show() ), otherwise hide it (( $(this).closest("tr").hide() )).

Considering that the format of dates coming from inputs is ...

dd/MM/aaaa

... for comparing dates, I've changed the order to ...

aaaa/MM/dd

For this I used .split("/") using array indexes to create a new date in the format above, so it is possible to compare dates.

Code sample:

$(document).ready(function(){
   
   $("#diaini, #diafim").on("input", function(){
      
      var dIni = $("#diaini").val();
      var dFim = $("#diafim").val();
      
      if(dIni.length == 10 && dFim.length == 10){
         
         var dIni_d = dIni.split("/");
         var dFim_d = dFim.split("/");
         
         dIni_d = dIni_d[2]+"/"+dIni_d[1]+"/"+dIni_d[0];
         dFim_d = dFim_d[2]+"/"+dFim_d[1]+"/"+dFim_d[0];
         
         $("#tabela tr").find("td:eq(1)").each(function(){
            
            var tab_dia = $(this).text().trim().substring(0,10);
            var tab_dia_d = tab_dia.split("/");
            tab_dia_d = tab_dia_d[2]+"/"+tab_dia_d[1]+"/"+tab_dia_d[0];
            
            tab_dia_d >= dIni_d && tab_dia_d <= dFim_d ?
            $(this).closest("tr").show()
            :
            $(this).closest("tr").hide();
            
         });
         
      }
      
   });
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Datainicial:<inputmaxlength="10" type="text" id="diaini">
Data final:
<input maxlength="10" type="text" id="diafim">
<br>

<table id="tabela" border="1">
   <tr>
      <td>
         1
      </td>
      <td>
         22/03/2018
      </td>
   </tr>
   <tr>
      <td>
         2
      </td>
      <td>
         21/03/2018
      </td>
   </tr>
   <tr>
      <td>
         3
      </td>
      <td>
         02/03/2018
      </td>
   </tr>
</table>
    
26.03.2018 / 22:51