Updated JavaScript for New Survey Taking Experience | XM Community
Skip to main content

Hello! 

I like to mask phone numbers in my surveys. I have successfully used the JS below to do that. 

In the new Survey Taking Experience, the JS no longer works. The published info on the new format does acknowledge that JS may need to be updated. Thing is… I don’t know JS and have no idea how to update it for it to work.

Can anyone help?

Here’s the code:

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

});

Qualtrics.SurveyEngine.addOnReady(function()
{
    jQuery(".InputText").on("cut copy paste",function(e) {
e.preventDefault();
});
jQuery(".InputText").on('keypress',function(){
if(event.which != 9 && isNaN(String.fromCharCode(event.which))){
event.preventDefault(); //stop character from entering input
}
var s = this.value.replace(/-/g,'');
if(s.length==10){
event.preventDefault();
}
if(s.length!=0){
if(s.length>=3 && s.length<=4){
var s1 = s.slice(0,3);
var s2 =s.slice(3,s.length);
this.value=s1+"-"+s2;
}
if(s.length>=6){
var s1 = s.slice(0,3);
var s2 =s.slice(3,6);
var s3=s.slice(6,s.length);
this.value=s1+"-"+s2+"-"+s3;
}
}

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

});

I’ve used “this.getQuestionContainer()” to safely scope the code to the current question only. Please try this. 

 

Qualtrics.SurveyEngine.addOnReady(function () {
    const phoneInput = this.getQuestionContainer().querySelector('inputttype="text"]');

    if (phoneInput) {
        phoneInput.addEventListener("cut", e => e.preventDefault());
        phoneInput.addEventListener("copy", e => e.preventDefault());
        phoneInput.addEventListener("paste", e => e.preventDefault());

        phoneInput.addEventListener("keypress", function (event) {
            if (event.key !== "Tab" && isNaN(event.key)) {
                event.preventDefault();
                return;
            }

            let s = this.value.replace(/-/g, '');

            if (s.length >= 10) {
                event.preventDefault();
                return;
            }

            setTimeout(() => {
                s = this.value.replace(/-/g, '');
                if (s.length >= 3 && s.length <= 5) {
                    this.value = s.slice(0, 3) + '-' + s.slice(3);
                } else if (s.length >= 6) {
                    this.value = s.slice(0, 3) + '-' + s.slice(3, 6) + '-' + s.slice(6, 10);
                }
            }, 0);
        });
    }
});
 


@Adeep Thank you! I’ll give this a shot.


x


Leave a Reply