Java script not working - help please | XM Community
Skip to main content

I have tried applying the script below to respect the logic of 

Action Behavior
Select option 3 5, 9, 11 become greyed out/disabled
Deselect 3 5, 9, 11 re-enable
Select any 3 total choices All other checkboxes grey out immediately
Deselect one The others re-enable
Submit Qualtrics still enforces “Min 1 / Max 3” validation

 

Qualtrics.SurveyEngine.addOnload(function() {
  // Define mutually exclusive options
  var exclusiveChoices = [3, 5, 9, 11];
  var maxChoices = 3;

  var questionContainer = jQuery(this.getQuestionContainer());

  // Handle exclusive logic
  function handleExclusive(selectedId) {
    var selectedInput = questionContainer.find("#" + this.getChoiceContainer(selectedId) + " input");
    var isChecked = selectedInput.is(":checked");

    exclusiveChoices.forEach(function(choiceId) {
      if (choiceId !== selectedId) {
        var input = questionContainer.find("#" + this.getChoiceContainer(choiceId) + " input");
        var label = input.closest("label");

        if (exclusiveChoices.includes(selectedId) && isChecked) {
          input.prop("checked", false);
          input.prop("disabled", true);
          label.css("opacity", "0.5");
        } else {
          input.prop("disabled", false);
          label.css("opacity", "1");
        }
      }
    }, this);
  }

  // Handle max-choices rule (live)
  function handleMaxChoices() {
    var checkedCount = questionContainer.find("input[type='checkbox']:checked").length;
    var allInputs = questionContainer.find("input[type='checkbox']");
    if (checkedCount >= maxChoices) {
      allInputs.not(":checked").prop("disabled", true).closest("label").css("opacity", "0.5");
    } else {
      allInputs.prop("disabled", false).closest("label").css("opacity", "1");
    }

    // Re-apply exclusive logic in case it was affected
    exclusiveChoices.forEach(function(choiceId) {
      var input = questionContainer.find("#" + this.getChoiceContainer(choiceId) + " input");
      if (input.is(":checked")) handleExclusive.call(this, choiceId);
    }, this);
  }

  // Attach change handlers
  this.getChoices().forEach(function(choiceId) {
    var input = questionContainer.find("#" + this.getChoiceContainer(choiceId) + " input");
    input.on("change", function() {
      handleExclusive.call(this, choiceId);
      handleMaxChoices.call(this);
    }.bind(this));
  }, this);
});

I’m not sure about the logic, I would have approached it a different way. A couple of things I noticed:

  1. The context of ‘this’ changes inside functions. You need to make a copy then use the copy inside other functions (e.g., var qobj = this at beginning of JS).
  2. Your use of this.getChoiceContainer(choiceId) is incorrect. getChoiceContainer doesn’t take an argument. You need to find the choice within the div it returns. 

Suggestion: make use of the browser console to debug.