Count instances within a Repeat using built-in system function (CountInstancesMydata())

It is often necessary to find out how many times (i.e. count) a particular field meets a certain condition within a Repeat. Doing this in long-hand script can be cumbersome, so we have included two built-in system functions that makes this easy: CountInstances() and CountInstancesMydata().

The CountInstancesMydata() is used when you want to count instances within a Repeat when the Repeat is on a different Form and you already have a multi-form data set, i.e. mydata.

The syntax for CountInstancesMydata is:

CountInstancesMydata('RepeatName', 'FieldName', 'Condition' );

The following script would count the instances where Field_1 equals ‘Bob’, and then place the answer in Field_2:

var count = CountInstancesMydata('RepeatName', 'FieldName', 'Condition' );

fld('Field_2').val(count);

If you need to count instances within a nested repeat, then you would use this syntax:

var count = CountInstancesMyData('//Gift_Level_1_rpt/*/Gift_Level_2_rpt/*', 'Gift_Condition_yn', 'true' );

fld('Field_2').val(count);

When the counting script is triggered within the Repeat, the count will update. But if a row within the Repeat is deleted (or added) then the count will not automatically be triggered. You need to trigger a re-count when these events happen to the Repeat rows. You do this with two system events, afterAdd() and afterRemove(). These functions needs to be called each time there is a change in the number of Repeats rows. So you need to include this script in the Form Script to trigger the counting each time the user adds a row or deletes a row. The name of the relevant Repeat is attached to the beginning of the function name:

function Repeat_rpt_afterRemove() {
   [function to be triggered, e.g. repeatLength()];
}

function Persons_rpt_afterAdd() {
   [function to be triggered, e.g. repeatLength()];
}