Skip to main content
November 30, 2016
Answered

counting fields which contain specific letter

  • November 30, 2016
  • 4 replies
  • 466 views

Hi

I have a form which has a series of different fields called "1st", "2nd", "3rd" etc all the way to "31st". The user is prompted to add either "ab" or "s" or a number to reflect the number of hours worked on the day or whether an employee was sick (s) or absent (ab).

The calculation for adding up the number of hours worked across the month is simple.

How do i add a custom calculation to add up the number of fields which either contain "s" or "ab"?

Cheers

This topic has been closed for replies.
Correct answer try67

Sure. You can use this code in that case:

var fields = ["1st", "2nd", ... , "31st"]; // replace "..." with the rest of the field names

var total = 0;

for (var i in fields) {

    var f = this.getField(fields);

    if (f.valueAsString=="s" || f.valueAsString=="ab")

          total++;

}

event.value = total;

4 replies

try67
Community Expert
Community Expert
November 30, 2016

This kind of naming scheme is not so good, because it's not very consistent. If you change it to something like "Hours1", "Hours2", "Hours31" then the code to do it will be much simpler.

If that's the case then you can use this code as the custom calculation script of the field where you want to show the result:

var total = 0;

for (var i=1; i<=31; i++) {

    var f = this.getField("Hours"+i);

    if (f.valueAsString=="s" || f.valueAsString=="ab")

          total++;

}

event.value = total;

If you leave it as you have it now then you'll need to hard-code the names of all of those fields in your code.

November 30, 2016

That's great - thanks!

Worse case scenario and i had to hard code the names of all those fields, can you give me an example of how the script would look?

Many thanks (i realise that's a pain in the ass request..)

try67
Community Expert
try67Community ExpertCorrect answer
Community Expert
November 30, 2016

Sure. You can use this code in that case:

var fields = ["1st", "2nd", ... , "31st"]; // replace "..." with the rest of the field names

var total = 0;

for (var i in fields) {

    var f = this.getField(fields);

    if (f.valueAsString=="s" || f.valueAsString=="ab")

          total++;

}

event.value = total;