Display Maximum Value Between 2 Fields

riaz_mansuri
Kilo Guru

Hi,

I am trying to create a script where the field displays the maximum value of 2 fields. So for example in Excel we would put in something like =MAX(D3:E3).

So in the below example Impact (Monetary) and Impact (Reputation) are both drop downs with a value of 1 - 5.

Impact max should display the maximum value (in the below case 5)

ImapctMax.JPG

Any help would be much appreciated.

Thanks

1 ACCEPTED SOLUTION

Hi Riaz,



Change the type onChange and select the field name as impact(reputation). Now paste the script as.


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


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


  return;


  }


  var a =   g_form.getValue('u_impact_monetary');


  var b = g_form.getValue('u_impact_reputation');


  var c = Math.max(a, b);


  g_form.setValue('u_impact_max',c);


  //Type appropriate comment here, and begin script below



}


View solution in original post

9 REPLIES 9

Ken83
Mega Guru

I think you can accomplish this in an onChange script utilizing the Javascript Math.max() method. Just pass in or comma separate the numbers you need to compare and that method will return the highest number among them.



Example: var highest = Math.max(5,3,21,8); // The highest variable is going to equal 21


Thanks Kenneth,



But where do I add the 2 fields I want to base this on?



Thanks


Riaz


Using the script that Pradeep Sharma provided...



var a =   g_form.getValue('u_impact_monetary');


var b = g_form.getValue('u_impact_reputation');


var c = Math.max(a, b);


g_form.setValue('u_impact_max',c);




The text "g_form.getValue()" is what you use to actually get the value of a field on your form. In between the parenthesis, you need to put in the name of the field as the first value. You can find that on the page where you edit the form, in the list of variables. The second value that goes in the parenthesis is the value that you want to set in that field. So the text he provided will look something like this(once you put the correct field names in). g_form.setValue('u_impact_max', c);




The first 2 lines are actually getting the values from the other 2 fields on the form...hope that makes sense. The 2 fields that you want to base this on, you need to create variables on the form for those unless you already have fields on the form that you want to use.






Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

Hi Riaz,



You can create a client script.Here you go.


var a =   g_form.getValue('fiedl1');


var b = g_form.getValue('field2');


var c = Math.max(a, b);


g_form.setValue('field3',c);



Replace the variable naming conventions and make sure you replace the fields with the exact column name