How to add two events in datepicker?

0

I need to make datepicker events added depending on where they clicked. For example: I need to filter some data by day and I can filter the same data also per month.

But with my code, only the month event is working because it is triggered when I click sometime next month

$('#calendario').datepicker({
      format: "yyyy-mm-dd",
      language: "pt-BR",
      startDate: '+0d'
  }).on('changeDate', function(e) {
      let data = e.format(0,"yyyy-mm-dd");
      location.href  = '/cursos?date=' + data;
  })
  .on('changeMonth',function(e) {
      let obj_mes = e.date;
      let mes = obj_mes.toString().split(' ');
      let mes_ano =  $(".datepicker-switch").html();
      let ano = mes_ano.split(' ');

      location.href  = '/cursos?mes=' + mes[1] + "&ano=" + ano[1];
  });
                    
asked by anonymous 06.03.2018 / 14:08

1 answer

0

You can capture all changes with onChange and within it compare the change of value in the dates to know which logic to apply.

Below is an example with explanatory comments:

$('#calendario').datepicker({
    format: "yyyy-mm-dd",
    language: "pt-BR",
    startDate: '+0d'
}).on("change", function(e){  

  //Pego o valor selecionado anteriormente
  var oldValue = $(this).attr("data-value");
  
  //Se não for a primeira alteração devo comparar as datas:
  if(oldValue != ""){
    date1 = novaData(oldValue);
    date2 = novaData($(this).val());
    
    if(date1.getFullYear() != date2.getFullYear()){
      console.log("Mudou o ano"); 
      //Coloque sua lógica se mudou ano
    }else if(date1.getMonth()+1 != date2.getMonth()+1){
      console.log("Mudou o mês"); 
      //Coloque sua lógica se mudou o mês
    }else if(date1.getDate() != date2.getDate()){
      console.log("Mudou o dia do mês"); 
      //Coloque sua lógica se mudou o dia do mês
    }
  }
  
  //Salvo a nova data selecionada no atributo data-value
  $(this).attr("data-value", $(this).val());
});

//Evita problemas com timezone ao definir a data
function novaData(dataString){
  var partes = dataString.split('-');
  var data = new Date(partes[0], partes[1] - 1, partes[2]); 
  return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><linkhref="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/css/bootstrap-datepicker.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.7.1/js/bootstrap-datepicker.min.js"></script><!--crioatributodata-valueparaarmazenarpenultimadataescolhida--><inputtype="text" name="calendario" id="calendario" data-value="" />
    
16.03.2018 / 14:53