I want to determine the Sunday and Saturday dates for the current week and then display them in survey fields. I have the following JavaScript which is close to working but doesn’t for some reason. Can someone tell me what is wrong? Thanks
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page is loaded*/
var today = new Date();
var dayOfWeek = today.getDay(); // 0 (Sunday) to 6 (Saturday)
// Calculate the date for the current week's Sunday
var sunday = new Date(today);
sunday.setDate(today.getDate() - dayOfWeek);
// Calculate the date for the current week's Saturday
var saturday = new Date(today);
saturday.setDate(today.getDate() + (6 - dayOfWeek));
// Format the dates as YYYY-MM-DD
var formatDate = function(date) {
var year = date.getFullYear();
var month = ('0' + (date.getMonth() + 1)).slice(-2);
var day = ('0' + date.getDate()).slice(-2);
return year + '-' + month + '-' + day;
};
var sundayDate = formatDate(sunday);
var saturdayDate = formatDate(saturday);
// Set the embedded data fields
Qualtrics.SurveyEngine.setEmbeddedData('SundayDate', sundayDate);
Qualtrics.SurveyEngine.setEmbeddedData('SaturdayDate', saturdayDate);
// Set the default values for the date fields
document.getElementById('Q1').value = sundayDate; // Replace 'QID1' with your question ID for Sunday
document.getElementById('Q2').value = saturdayDate; // Replace 'QID2' with your question ID for Saturday
});