Custom validation code for matrix table with text entry with 2 statement | XM Community
Skip to main content

Hello, 

I have a question where I require the respondent to enter minimum value and a maximum value. I wish to add custom validation such if the minimum value entered is less than or equal to 0, it displays an error saying “The value entered for the first statement must be greater than 0." and if the maximum value is less than the minimum value, it displays an error saying “The value entered for the second statement must be greater than or equal to the value entered for the first statement."

I am using a matrix table format with text entry for this question and am trying to use the following JavaScript code but it is not working. Any help would be appreciated in how to fix/ work around this.

Thanks

 

 

Qualtrics.SurveyEngine.addOnload(function() {
    var q = jQuery("#" + this.questionId);
    var ve = q.find(".ValidationError");
    var inputText1 = q.find(".InputText:eq(0).val()"); // First input in the matrix
    var inputText2 = q.find(".InputText:eq(1).val()"); // Second input in the matrix
    var nextButton = jQuery("#NextButton");

    inputText1.on("blur", function(e) {
        validateInputs();
    });

    inputText2.on("blur", function(e) {
        validateInputs();
    });

    function validateInputs() {
        var value1 = parseFloat(inputText1.val());
        var value2 = parseFloat(inputText2.val());

        if (isNaN(value1) || isNaN(value2)) {
            displayErrorMessage("Please enter valid numbers for both statements.");
        } else if (value1 <= 0) {
            displayErrorMessage("The value entered for the first statement must be greater than 0.");
        } else if (value2 < value1) {
            displayErrorMessage("The value entered for the second statement must be greater than or equal to the value entered for the first statement.");
        } else {
            hideErrorMessage();
        }
    }

    function displayErrorMessage(message) {
        ve.html('<span style="color: red;">' + message + '</span>');
        ve.show();
        // Disable the "Next" button
        nextButton.prop("disabled", true);
    }

    function hideErrorMessage() {
        ve.html('');
        ve.hide();
        // Enable the "Next" button
        nextButton.prop("disabled", false);
    }
});

inputText1 and inputText2 are values, so you can’t attach event handlers to them. Remove .val() from the lines where you assign them so that they refer to elements.


Leave a Reply