using javascript to validate text entry responses | XM Community
Skip to main content

I tried using the following javascript, to only allow certain responses to a text entry question. However, it is not working. Any suggestions?

 

Thanks a lot in advance.

 

Qualtrics.SurveyEngine.addOnPageSubmit(function() {
// Target the text entry question by its QuestionID
var questionId = 'QID1';

// Specify the pre-specified options
var validOptions = ='Option 1', 'Option 2', 'Option 3'];

// Get the entered value from the text entry question
var enteredValue = this.getChoiceValue(questionId);

// Check if the entered value is not one of the valid options
if (!validOptions.includes(enteredValue)) {
this.setChoiceError(questionId, 'Please enter a valid option.');
this.disableNextButton(); // Disable the next button
} else {
this.clearChoiceError(questionId);
this.enableNextButton(); // Enable the next button
}
});

 

You should use Custom Validation instead of JavaScript.  Without going into details on your JS, you’ve misunderstood how a number of things work.


Thanks Tom. However, I have hundreds of text options to put in, instead of 3 in the attempted code. Could you provide some hints to correcting the code?


In that case, I recommend using a multiple choice question with a dropdown instead of a text entry question. You could use select2 to make it searchable.

Another option might be Supplemental Data if you have that feature on your Qualtrics account.


Thanks Tom. I will give select2 a try and report back.


Dropdown + select2 worked nicely!


I concluded too early. I ran into a problem with the 20,000 character limit when I input all the options. Any other idea to solve this?


You can use a text entry question. Add you own select in the question text html. Use JS to hide the text input, add select2, and copy the select value to the text entry on update or submit.


The idea is brilliant, but I hit the 20,000 character limit again when I added my select in html.


Two more options:

  1. Use an empty select and load the options from a JS object using select2.
  2. If you hit a limitation, load them from a server using select2 ajax option.

Empty select worked. Grateful for your advice, Tom!

P.S. In case it is useful for future visitors to this page -- if there is ‘ in one of the options, need to escape it to make the code work. This took me the longest time to figure out...


Leave a Reply