J Miller
J Miller

Reputation: 437

qualtrics javascript: date-triggered logic

Qualtrics does not provide logic based on dates, and I would like to create an alert triggered by a date input by a user. Specifically, I would like an in-page text to appear (not an alert dialog box) if a user enters a date that is within 30 days of today.

I've cobbled together a short script that gets me part way there (it calculates and compares dates), but I'm a javascript novice and need some pointers.

var today = new Date();
var m = today.getMonth();
var d = today.getDate();
var y = today.getFullYear();

var date = new Date(y,m,d)+30;

var mydate="${q://QID1/ChoiceTextEntryValue}";
var mydate = parseInt(mydate);

console.log(date);
console.log(mydate)

if(date>mydate)
{
    alert(mydate + " is greater than " + date);
}
else
{
    alert(mydate + " is smaller than " + date)
}

This script runs when a page loads, but I don't want it to run until the user enters a date in a text field. What needs to be added to the script to tell it to wait for the user? Where is the best place in a qualtrics form to put my script?

If I want in-form text to appear on the basis of my date calculation (as opposed to an alerts dialog box), should I write embedded data to the form and use qualtric logic condition to display the in-form text?

Thanks in advance for teaching me what I'm sure is basic javascript knowledge.

Upvotes: 0

Views: 475

Answers (1)

T. Gibbons
T. Gibbons

Reputation: 5004

Not a complete solution, but answers to your questions:

1) You want a function that executes when you lose focus on the date input field. Something like the following where dateElement is the input field:

dateElement.observe("blur", function(event) {
    // function code goes here
}); 

2) Add your javascript to the question by clicking "Add Javascript" from the drop down menu on left of the question.

3) You can put your condition display text inside a <span> tag in your question text and turn display on or off from your javascript. You can update the text inside the span using innerHTML. span would be something like this:

<span id="displayText" style="display:none"></span>

Javascript would be something like:

$('displayText').innerHTML = mydate + " is smaller than " + date;
$('displayText').show();

You didn't ask, but you should probably use something like moment.js to do the date calculations.

Upvotes: 1

Related Questions