How to add two events in datepicker?

Asked

Viewed 724 times

0

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

But with my code, it’s only working the event of the month because it’s triggered when I click on some day of the following 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];
  });
  • These events will only capture if the user clicks on the datepicker, if he type in the input will not work, I suggest treating everything in "change"

  • But in "change" he misses the event when he changes the year

1 answer

0


You can capture all changes with onChange and within it compare the change in value on 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>
<link href="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>

<!-- crio atributo data-value para armazenar penultima data escolhida -->
<input type="text" name="calendario" id="calendario" data-value="" />

Browser other questions tagged

You are not signed in. Login or sign up in order to post.