Need help with Javascript code to get custom validation | XM Community
Skip to main content

Hi all - I’m trying to set up custom JS code to restrict the participants who respond to my survey. Specifically, I am trying to only have respondents that use firefox or safari (no chrome or edge). To do this, I created a text question at the start which just says “checking your browser”, and added the following JS code:

Qualtrics.SurveyEngine.addOnload(function() {

    var ua = navigator.userAgent;

    var browserName;

 

    if (ua.indexOf("Chrome") > -1) {

        browserName = "Chrome";

    } else if (ua.indexOf("Safari") > -1 && ua.indexOf("Chrome") === -1) {

        browserName = "Safari";

    } else if (ua.indexOf("Firefox") > -1) {

        browserName = "Firefox";

    } else if (ua.indexOf("MSIE") > -1 || !!document.documentMode === true) {

        browserName = "IE";

    } else {

        browserName = "Unknown";

    }

 

    if (browserName !== "Safari" && browserName !== "Firefox") {

        alert("Your browser is not supported. Please use Safari or Firefox. Please return the HIT");

        // Prevent form submission

        document.querySelector("form").addEventListener("submit", function(event) {

            event.preventDefault();

        });

        // Hide the Next button

        var nextButton = document.querySelector(".NextButton");

        if (nextButton) {

            nextButton.style.display = "none";

        }

    }

});

 

 

While this works in restricting the browser, it still allows people to continue on Chrome if they click ok on the alert and then continue on. So, I’d like to modify the code or add custom validation such that if someone is using a non-supported browser (like chrome or edge), they should have an error that prevents them from continuing. I’d greatly appreciate if someone can show the code I need to achieve this.

 

Thanks!

Hi @IndyMuk,

try it with the addOnReady method instead of the addOnload. 🙂

Best
Christian


Leave a Reply