javascriptqualtrics

Qualtrics Javascript focus / select / place cursor on text box when page loads


I am trying to make Qualtrics focus automatically on a text box (single question per page) so participants can start typing right away.

I have tried different things from other answers (e.g.,Qualtrics: Automatic blinking cursor (focus) does not work on JFE, only on SE surveybuilder) but the focusing doesn't work on browsers like IE (Firefox, without including code, automatically focuses on the question).

The code also seems to invalidate code for advancing to next page by pressing "Enter" (below), so the survey gets stuck on the page

Qualtrics.SurveyEngine.addOnload(function()
{
 this.hideNextButton();
 this.hidePreviousButton();
 var that = this;
 Event.observe(document, 'keydown', function keydownCallback(e) {
  var choiceID = null;
  switch (e.keyCode) {
   case 13: // 'enter' was pressed
    choiceID = 1;
    break;
  }

  if (choiceID) {
   Event.stopObserving(document, 'keydown', keydownCallback);
   that.clickNextButton();
  }
 });
});

Any ideas how to fix this? thank you!


Solution

  • The problem with your code may be hideNextButton with addOnload due to timing issues. Use addOnReady instead. Also, it is best to check for the existence of the PreviousButton first. If is is not there it will cause an error and stop your script. On some browsers you have to select a field before you can focus on it, activate() does that. Finally, it is better to add your event handler to the text field, instead of the document.

    Try this:

    Qualtrics.SurveyEngine.addOnReady(function()
    {
     $('NextButton').hide();
     if($('PreviousButton')) $('PreviousButton').hide();
     var inputText = $(this.questionId).down('.InputText');
     var evt = inputText.on('keydown', function(e) {
       if(e.which == 13) {
         evt.stop();    
         $('NextButton').click();
       }
     });
     inputText.activate();
    });