How To:Totaling Values in a Repeating Table
How To:Totaling Values in a Repeating Table
Repeating tables are one of the easiest ways to organize groups of data within an InfoPath form. These tables provide an easy column/row based metaphor to quickly update grouped data. A common task within a repeating table is to total several column values and store the results in another column. In this example, I will show you a quick way this can be done using script.
Let’s assume that we have a simple data structure that contains a repeating group that is designed to capture employee timesheet entry. Within an InfoPath data structure this would be designed as follows.

When dragged onto an InfoPath form, this group structure can be placed into a repeating table. The purpose of this repeating table is to allow end users to enter their starting work time and ending work time for a specific date. The sum of these two times (starttime and endtime) is then placed into totaldayhours element. This element contains the total amount of hours that a particular user has worked for the day. Within an InfoPath form this repeating table would resemble the following.

The following are the steps necessary to update the totaldayhours field based on properly formatted times being entered.
- Set the “totaldayhours” field to Read Only. Although, not a requirement it will prevent users from inadvertently updating this field.

- In the “OnAfterChange” event for the endtime field add the following script.
function msoxd_timesheet_endtime::OnAfterChange(eventObj)
{
// Write code here to restore the global state.
if (eventObj.IsUndoRedo)
{
// An undo or redo operation has occurred and the DOM is read-only.
return;
}
// A field change has occurred and the DOM is writable. Write code here to respond to the changes.
updatehoursworked(eventObj)
}
That will then call this function that does the actual work
function updatehoursworked(xmlitem)
{
var nhours = 0;
varstarttime = 0;
var endtime = 0;
starttime = parseFloat(xmlitem.Site.previousSibling.previousSibling.text);
endtime = parseFloat(xmlitem.Site.text);
if (starttime==0){return;}
if (starttime > endtime){
nhours += (24 - starttime) + endtime;
}
else{
nhours += endtime - starttime;
}
xmlitem.Site.nextSibling.nextSibling.text = nhours;
}
Once a user enters and leaves the endtime element, this forces the calculation within the “OnAfterChange” event that updates the totaldayhours field as shown below.