Search code examples
javascriptdom-eventsqualtricsonblur

Qualtrics API functions not working within custom function called in EventListener


I defined a custom function in the header section that checks, alerts the user, and resets the value of a particular slider bar when it fails certain restrictions.

This function works beautifully when called on question clicks:

  this.questionclick = chkVals;

I would like to also run the function when the user are exiting the text input field (as some users are using the keyboard to do the survey). I implemented an Event Listener for each sliders' text input field that runs the function when the focus is out of the text input field.

// choices is an array of choice ids 
  for (i = 0; i < choices.length; i++) {
    var x = document.getElementById(choices[i]);
    x.addEventListener("blur", chkVals, true);
  };

I know that the event listener works, because the correct alerts are popping up. It is just not able to reset the values as this.setChoiceValue is not a function within the environment. I have tried setting var that = this; and calling that.setChoiceValue in the function, but it still does not work.

Any help will be greatly appreciated!


Solution

  • @T. Gibbons 's answer helped me get to this point. As suggested I needed to add a parameter to chkVals() to be able to reference the this object. However,

    this.questionClick = chkVals(this);
    

    does not work due to this being a reserved object, so the whole header script will not run. I ended up changing all reference of this to that in my custom function and adding the parameter that as suggested:

    function chkVals(that) {
    ...
    ... that.setChoiceValue(x, y)
    }
    

    To call the function with a parameter, I had to explicitly defined an anonymous function that called chkVals, otherwise it will not work (I am not sure why):

      var that = this; 
    
      this.questionclick = function() {chkVals(that);}
    
      for (i = 0; i < choices.length; i++) {
      var x = document.getElementById(choices[i]);
      x.addEventListener("blur", function() {chkVals(that);}, true);
    
      };
    

    The above works!