Disable input of content after adding 300 letters and show number of entered letters | XM Community
Skip to main content

Hi community,

 

I would like to know what is best way to solve this as after exploring it seems that it will require java script.

We want the doctors to enter instrument names instead of the reason. The instrument names are usually lower than 300 letters. We would like to 

  1. Disable input after 300 letters are entered
  2. Show the characters entered/remaining(if that is possible)

 

@R_cstalin Try this… 🙂 The comments should explain the logic. If you have any questions, let me know. 

Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/

});


Qualtrics.SurveyEngine.addOnReady(function() {
var textarea = document.querySelector("textarea");
var maxLength = 300;

// Check if listener is already added
if (!textarea.dataset.listenerAdded) {
// Create a counter element
var counter = document.createElement("div");
counter.id = "charCounter";
counter.style.marginTop = "10px";
counter.style.fontSize = "14px";
counter.style.color = "grey";
textarea.parentNode.insertBefore(counter, textarea.nextSibling);

// Function to update the counter and manage text length
function updateCounter() {
var currentLength = textarea.value.length;

if (currentLength > maxLength) {
textarea.value = textarea.value.substring(0, maxLength);
currentLength = maxLength;
}

counter.textContent = currentLength + " / " + maxLength + " characters";

// Change counter text color to red if the maximum length is reached
if (currentLength === maxLength) {
counter.style.color = "red";
} else {
counter.style.color = "grey";
}
}

// Update counter on input and manage text length
textarea.addEventListener("input", updateCounter);

// Mark that the listener has been added
textarea.dataset.listenerAdded = "true";

// Initial counter update
updateCounter();
}
});

Qualtrics.SurveyEngine.addOnUnload(function()
{
/*Place your JavaScript here to run when the page is unloaded*/

});

In addition to your requirements, I also changed the text color of the “300 / 300 characters” to red once the 300 limit is reached. If you do not want that, just comment this line: 

counter.style.color = "red";

Works perfectly fine for me: 

With maximum characters reached: 

Best
Christian


Leave a Reply