Start a conversation

Calculating with checkbox fields

Check if a box was checked

Checkbox fields get saved as a semi-colon separated string, e.g. "1;4;5". To be able to perform calculations with these values, you have to split the string in separate values and check if a specific value of interest is in the collection of values. For example, to check whether a checkbox with the option value 5 was checked, you can use: 

var splitted = "{variable_name}".split(';');
if (splitted.indexOf("5") > -1) {
    1;
} else {
    0;
}

 This will return 1 if that option was checked or 0 if it wasn't. Replace variable_name with your own checkbox variable and '5' with your values of interest.


Retrieve the highest or lowest value of the selected checkboxes

You can use Math.max.apply() and Math.min.apply():

var splitted = "{variable_name}".split(';');
Math.max.apply(null, splitted);

This will return the maximum value from the selected checkbox values. 


Calculate the sum of multiple options of a checkbox field

var splitted = "{variable_name}".split(";");
var myTotal = 0; // Variable to hold your total
for(var i = 0, len = splitted.length; i < len; i++) {
   myTotal += Number(splitted[i]); 
}
myTotal;

In the third line, a for loop iterates over the values of your checkbox fields that are selected.


Calculate the amount of checked boxes of the checkbox field 

var splitted = "{variable_name}".split(";")
splitted.length;

Please note that "splitted.length" will always be > 1. 


Calculate if any checkbox was selected

'##allowempty##'; 
if ("{variable_name}" == "'NA'") {
  'Checkbox is empty'
};  


Calculate how many checkboxes are selected and their total sum

var string = "{check_boxes}".split(";");
var myTotal = 0;
var sum = 0;
for (var i = 0; i < string.length; i++) {
    if (string.indexOf(string[i]) > -1) {
        myTotal = myTotal + 1;
        sum = sum + parseInt(string[i]);
     }
};
"There are " + myTotal + " selected checkboxes with a total sum of " + sum + " .";
Choose files or drag and drop files
Was this article helpful?
Yes
No
  1. Tonya

  2. Posted
  3. Updated