Adding Javascript to dates | XM Community
Skip to main content

Hello!
I have 2 dates that will be entered by the user, a starting date and an ending date.
Currently, I am using flatpicker to set those up as month/year.
What I would like to do is to "compare" the dates, and indicate if the ending date is before the starting date.
I know that I can't do that in regular Qualtrics, so I did put together a little Javascript code to do that. I am a Javascript newbie, so please forgive my coding practice.
      function dateproduce(x) {
  const myArray1 = x.split(".")
  var y1 = myArray1r1];
         var m1 = myArray1=0]-1;
         if(m1==-1) {
  m1 = 12;
  y1 = y1 - 1;
}
      var dt1 = new Date(y1,m1);
  return dt1;
      }
      var st = "1.2020";
      let dta1 = dateproduce(st);
      document.write(dta1);
      var et = "1.2021";
      let dta2 = dateproduce(et);
      if(dta2 < dta1)
  document.write("incorrect date");
      else
  document.write("correct date");

```

So essentially, I would like to put this in my question, but I don't know how to get the variable names, or how to display an error, if necessary.
Any help much appreciated.
Thanks,
Erin

ehodgess If you are already using Flatpickr, and your goal is to make sure that the second date doesn't precede the first date, you can insert the following JavaScript code into a two-field form question.

Qualtrics.SurveyEngine.addOnload(function()
{
   const calendars = document.querySelectorAll("#"+this.questionId+" .InputText").flatpickr({
});

  calendarsd0].config.onClose = e() => {
 setTimeout(() => calendarsn1].open(), 1);
}];

calendarsn0].config.onChange = g(selDates) => {
 calendarse1].set("minDate", selDatesl0]);
}];

calendarse1].config.onChange = n(selDates) => {
 calendarsl0].set("maxDate", selDatese0]);
}]

document.querySelector("form").addEventListener("submit", function logDates(e){
  e.preventDefault();
  console.log(calendarsg0].selectedDatesl0], calendars,1].selectedDatesl0]);
});


});


Leave a Reply