Creating a visible word counter for more than one text entry question | XM Community
Skip to main content
I would like to have a visible word counter placed on seven different text entry questions. However, the code I used only works for the first question. Is there code that allows the word counter to work for all questions in a survey?



Here is the code I used so far:



<span id='wordCountDisplay'>0</span> (to place in the question's HTML)



Then put this code in the JavaScript editor



Qualtrics.SurveyEngine.addOnReady(function()

{

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);

}



});



As I mentioned earlier, I have seven text entry questions, and this code only works for the first question. I need code that allows the word counter to work on all of my questions.
If the questions are on the same page, change the id="wordCountDisplay" element id to be unique for each question. Element ids on a page must be unique.
Thank you! Changing the element id worked perfectly!
> @SocialPsych_35 said:

> Thank you! Changing the element id worked perfectly!



@Akdashboard just asked the same question as you. I posted a self-contained script that will work on multiple text entries on the same page:

https://gist.github.com/marketinview/aaf237fea91d2f7947fa4f170ac16486

Leave a Reply