Calculated Field on Catalog Item

alexcharleswort
Tera Expert

So, I know how to do this pretty easily on a custom table, but I am looking to do this on a catalog item. I have the variables tra_tuition0, tra_tuition1, and tra_tuition3. On change of these, I want them to automatically fill out tra_tuition_total with the sum of those three numbers?

Thanks in advance for your help!

6 REPLIES 6

Chuck Tomasi
Tera Patron

Hi Alex,



You will need to write an onChange client script for each of the fields to recalculate the total.



http://wiki.servicenow.com/index.php?title=Creating_a_Catalog_Client_Script


Uncle Rob
Kilo Patron

So on Catalog Items you're not dealing with a "real" field, but rather a variable.  


In this case you're going to do all your math work via a Catalog Client Script.   I'm not sure if you can pull it off with just one either.   Client scripts will trigger on the change of a field, so you might need a client script for each of the fields that contribute to the total.


Uncle Rob
Kilo Patron

The script is going to look like this.   I'm not sure how you can get this to work in just one script... so you'll have to do this for each component of the total and make subtle changes for each.



Catalog Client Script:   On Change of variable tra_tuition1



function onChange(control, oldValue, newValue, isLoading) {


  if (isLoading || newValue == '') {


          return;   //do nothing if the old and new values match.


  }



  var tui1 = newValue;   //assuming this is the script for Tuition1, we want the newest value in the field.


  var tui2 = g_form.getValue('tra_tuition2');


  var tui3 = g_form.getValue('tra_tuition3');


  var total = Number(tui1) + Number(tui2) + Number(tui3)   //make certain they're numbers before summing.


  g_form.setValue('tra_tuition_total', total);



}



There's probably a dozen ways to make that more elegant, but that should work.


Yeah I was hoping to get this on one script, but I think you're right, it's not going to happen. I'm also unable to get the tra_tuition_total to reflect if the user goes back and deletes out anything from the tra_tuition fields - it only add them correctly if there is a value in that field or that field is zero. So, my work around now is trying to figure out how to get the tra_tuition fields to automatically fill in with 0.00 if the user deletes the value from those fields.


I just cant quite seem to get the client scripts to read "if ( newValue == ' ')"...



Unless you have any other suggestions.