word limit: giving me a word limit error if the text contains characters | XM Community
Skip to main content

here is my javascript code:
Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
var display = $('wordCountDisplay');
  var questionID = this.questionId;
  var textbox =$('QR~' + questionID);
  var that = this;
  function countWords(s){
    s = s.replace(/\\n/g,' '); // newlines to space
    s = s.replace(/(^\\s*)|(\\s*$)/gi,''); // remove spaces from start + end
    s = s.replace(/ ]{2,}/gi,' '); // 2 or more spaces to 1
      if(s == ''){
        return 0; 
      }else{
        return s.split(' ').length; 
      }
  }
  textbox.onkeyup = function(e){
    display.update(countWords(textbox.value));
    console.log(textbox.value);
  }
});
custom validation is set to Matches Regex with ^(?:\\b\\w+\\br\\s\\r\\n]*){0,200}$
how can l fix it

Hey! Your jQuery selectors are a touch off. I assume you're trying to get the elements by Id. If yes, then you'll need the pound sign inside the single brackets of your $() tag.
So this:
var display = $('wordCountDisplay');
Becomes this:
var display = $('#wordCountDisplay');
And so on.

Also, strings in JS are immutable, I believe, so I don't think your CountWords function will be able to just overwrite string s like you think it should. you can either rename s each time you want to overwrite it, returning the final mutation (clunky), use a string builder to return a new string, or change your regex to do the whitespace trimming and split on spaces all in one line that you return as newS (probably my suggestion here).


Leave a Reply