How to Calculate Total Duration from Monday to Friday Catalog Variables and Store in Another variabl
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-22-2025 03:51 PM - edited 06-22-2025 03:53 PM
Hi everyone,
I'm working on a Service Catalog Item that contains several duration-type variables for working hours from Monday to Friday (e.g., monday, tuesday, ..., friday). Each variable represents daily working hours (e.g., 6 hours 30 mins per day).
I also have two other duration-type variables:
contractual_weekly_working_hours→ represents the contractual total weekly hours (e.g., 37 hours)
total_hours_of_working_week → This should automatically calculate the sum of Monday to Friday durations. This should be read-only and error message should be visible when it does not match with the stated contractual_weekly_working_hours.
I am not good at scripting and I have never done calculation like this before. Therefore I really appreciate you help.
😇
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-22-2025 07:36 PM
please share the variable config screenshots and what you tried so far.
I assume you have 5 variables for each of the working day
write this onChange client script on each of the variable for working day
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
// Get daily values in seconds (duration variables return seconds)
var days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday']; // give your variable name here
var total = 0;
days.forEach(function(day) {
var val = g_form.getValue(day);
total += val ? parseInt(val, 10) : 0;
});
// Set the total to the read-only variable
g_form.setValue('total_hours_of_working_week', total);
// Compare with contractual weekly hours
var contractual = parseInt(g_form.getValue('contractual_weekly_working_hours'), 10) || 0;
// Remove previous error
g_form.hideFieldMsg('total_hours_of_working_week', true);
if (contractual !== 0 && total !== contractual) {
g_form.showFieldMsg('total_hours_of_working_week',
'Total working hours do not match contractual weekly hours!',
'error');
}
}
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader