javascriptsurveyjs

Make number of rows in a matrix equal to a previous answer


I am writing a survey in SurveyJS and I would like the number of rows in a survey to equal a previous answer. It would be something like this, except that this fails:

const surveyJson = {
  "elements": [
    {
      "type": "text",
      "name": "num_classrooms",
      "inputType": "number",
      "min": 1,
      "max": 20,
      "title": "How many classrooms do you teach in this school?",
      "isRequired": true
    },
    {
  "type": "matrixdynamic",
  "name": "familyMatrix",
  "title": "Classroom Information",
  "columns": [
    {
      "name": "name",
      "title": "Name",
      "cellType": "text"
    },
    {
      "name": "age",
      "title": "Age",
      "cellType": "number"
    }
  ],
  "rowCount": "{num_classrooms}",
  "minRowCount": "{num_classrooms}",
  "maxRowCount": "{num_classrooms}"
    }
  ]
}

I know that I can let the user add or delete rows in a matrix, but for clarity I prefer that the user first give the number of classrooms and only after fill information.

I searched online for an answer and also tried AI, but couldn't find a solution. The problem is similar to this question from Kobo Toolbox: asking for number of household members and adding a row for each member.

How can I do the same in SurveyJS?


Solution

  • Perhaps using dependencies, You could do something like

    visibleIf: "{num_classrooms} >= 1",
    

    But I think you do need an event handler - for example this, using a batch update to not trigger an update per matrix.???rowCount

    survey.onValueChanged.add(function (sender, options) {
      if (options.name === "num_classrooms") {
        const num = parseInt(options.value, 10) || 0;
        const matrix = sender.getQuestionByName("classroomMatrix");
        
        if (matrix) {
          matrix.beginUpdate();
            matrix.rowCount = num;
            matrix.minRowCount = num;
            matrix.maxRowCount = num;
          matrix.endUpdate();
        }
      }
    });