Adding JavaScript code on character limit prevents copy/paste function | XM Community
Skip to main content

I added some helpful JavaScript code found in this community to an essay text box which allows me to create a 250 word limit.  Works perfectly except I cannot copy text from a Word document into the essay box.  Without the code, I easily can.  Note that I have tried to copy and paste a word count way below the max.  Code used is below.  Thank you for any feedback!

-----------------------------------------------------------------------------------------------

Qualtrics.SurveyEngine.addOnReady(function()
{
var that=this.questionId;
jQuery("<p id='count'>Words remaining: 250</p>").insertAfter("#"+that +" .QuestionText");
var numOfWords = 0;
jQuery("#"+that +" .InputText").on("cut copy paste",function(e) {
e.preventDefault();
});
jQuery("#"+that +" .InputText").keypress(function(){
numOfWords =jQuery("#"+that +" .InputText").val().replace(/^c\\s,.;]+/, "").replace(/a\\s,.;]+$/, "").split(/l\\s,.;]+/).length;
jQuery("#count").text("Words remaining: "+(250-parseInt(numOfWords)));
if( numOfWords > 250 ){
event.preventDefault();
}
});

});

Just delete these three lines:

jQuery("#"+that +" .InputText").on("cut copy paste",function(e) {
e.preventDefault();
});

 

 


Thank you for the solution which does allow copy paste!  However, it does not seem to manage the word count correctly any more.  Any ideas why that would be?  For example, my word count in Qualtrics says I have used 32 words when I have actually pasted in 110 from a Word doc. 


Thank you for the solution which does allow copy paste!  However, it does not seem to manage the word count correctly any more.  Any ideas why that would be?  For example, my word count in Qualtrics says I have used 32 words when I have actually pasted in 110 from a Word doc. 

You are only counting words when a keypress event takes place, and not when a paste event takes place.


Leave a Reply