Adding Javascript to dates | XM Community
Skip to main content
Question

Adding Javascript to dates

  • August 7, 2022
  • 1 reply
  • 37 views

Forum|alt.badge.img

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 = myArray1[1];
         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

1 reply

jmborzick
QPN Level 5 ●●●●●
Forum|alt.badge.img+41
  • QPN Level 5 ●●●●●
  • 249 replies
  • September 27, 2022

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({
});

  calendars[0].config.onClose = [() => {
 setTimeout(() => calendars[1].open(), 1);
}];

calendars[0].config.onChange = [(selDates) => {
 calendars[1].set("minDate", selDates[0]);
}];

calendars[1].config.onChange = [(selDates) => {
 calendars[0].set("maxDate", selDates[0]);
}]

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


});


Leave a Reply