Javascript for keypress within multiple choice question | XM Community
Skip to main content

I would like to present a typical multiple choice question, but allow participants to complete it in either the typical fashion (select a response then click continue) or by pressing a specific key (right bracket), at which point the question will auto-forward to the next question. I am able to do this with the following added to Qualtrics.SurveyEngine.addOnReady:
/* Allow right bracket to auto-advance this question. */ 
var that = this;
Event.observe(document, 'keydown', function keydownCallback(e){
var choiceID = null;
if (e.keyCode == 221) 
{
Qualtrics.SurveyEngine.setEmbeddedData( 'PassAttChk', 1 );
Event.stopObserving(document, 'keydown', keydownCallback);
that.clickNextButton();
}
This actually works okay, but the problem is that it continues to catch the keypress in subsequent questions. I've tried adding this to Qualtrics.SurveyEngine.addOnUnload
Event.observe(document, 'keydown', function keydownCallback(e){ });
But it either does not function or stops the initial keypress from being caught.
Any idea what I'm doing wrong here? Thanks!!

Hi there, in testing on my end, the code you posted works on only 1 question, but will work on whichever question first experiences the right bracket key. So even if the JS is configured on the first question, the listening continues even if it is not pressed until the third question. I was able to have the keypress only work on the configured question by stopping the event observer on page submit. If you still need, try using the below JS:
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/

});


Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/

let that = this;

Event.observe(document, 'keydown', function keydownCallback(e){

if (e.keyCode == 221) 
{
Qualtrics.SurveyEngine.setEmbeddedData( 'PassAttChk', 1 );
that.clickNextButton();
}

})

});


Qualtrics.SurveyEngine.addOnUnload(function()
{
/*Place your JavaScript here to run when the page is unloaded*/

});


Qualtrics.SurveyEngine.addOnPageSubmit(function(type)   
{
/*Place your JavaScript here to run when the page is unloaded*/

Event.stopObserving(document, 'keydown')

});


Leave a Reply