How do I set an embedded data field equal to the word count of a text entry question? | XM Community
Skip to main content

Hi all,
I'm a novice with JS trying to cobble together a few related ideas from other posts.
Goal: Set an embedded data field

r1_wordcount
equal to the total number of words from a text entry field (in case it matters, the name of the text entry question is
r1_typing
). In a later block, I want to show participants that value (e.g., "Your answer contained ${e://Field/r1_word_count} words").
Not knowing JS myself, I've tinkered with other postings and come up with this as my best guess:
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
});

Qualtrics.SurveyEngine.addOnReady(function()
{
/*Place your JavaScript here to run when the page is fully displayed*/
    var questionID = questionId;
    var textbox =$('QR~' + questionID);
    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; 
            }
    }
});


Qualtrics.SurveyEngine.addOnUnload(function()
{
/*Place your JavaScript here to run when the page is unloaded*/
Qualtrics.SurveyEngine.setEmbeddedData("r1_wordcount", countWords(textbox.value));
});
Any help would be appreciated.

THANKS!

Use the below code:
Qualtrics.SurveyEngine.addOnPageSubmit(function(type)
{
if(type == "next")
{
var regex = /\\s+/gi;
var c =0;
c = jQuery("#"+this.questionId+" .InputText").val().trim().replace(regex, ' ').split(' ').length;
Qualtrics.SurveyEngine.setEmbeddedData("r1_word_count", c);
}
});


@rondev for president!
Yes, yes, yes! This is great. Thanks a ton!


Leave a Reply