OnChange Loop

jamesmcwhinney
Giga Guru

I have a need to adjust the value of a field after a user edits it.

I wont go into the specifics as its not relevant.

My problem is that as soon as I try to adjust the field,. I create an infinite loop.

This should be such an easy problem to fix on a regular html/javascript page,.   but I have burned a couple hours now trying to figure out how to prevent it in ServiceNow...

Any help would be appreciated!

Below is a sample to reproduce the loop.

(The name of the variable is item3_cost)

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

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

          return;

    } else {

      //Adjust the value entered

      newValue += 'testadjustment';

      alert('the value is now ' + newValue);

      g_form.setValue('item3_cost',newValue);

      return;

    }

}

1 ACCEPTED SOLUTION

jamesmcwhinney
Giga Guru

Figured it out....




function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
          //Do Nothing
    } else {
      var fixedValue = ''+getNumber(newValue);
     
      //Only update the field if it has changed (to prevent loop)
      if(fixedValue != newValue){
        g_form.setValue('item3_cost',fixedValue);
      }
}
return;
}


function getNumber(string){
//Try numberize and set Cost to Zero if it is not a number
     
string = string.replace('$', '');
string = string.replace('â‚®', '');
string = string.replace(',', '');
string = string.replace(' ', '');

if(!isNaN(parseFloat(string)) && isFinite(string)){
  return parseFloat(string);
} else {
  return 0;
}
}


View solution in original post

2 REPLIES 2

jamesmcwhinney
Giga Guru

Figured it out....




function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
          //Do Nothing
    } else {
      var fixedValue = ''+getNumber(newValue);
     
      //Only update the field if it has changed (to prevent loop)
      if(fixedValue != newValue){
        g_form.setValue('item3_cost',fixedValue);
      }
}
return;
}


function getNumber(string){
//Try numberize and set Cost to Zero if it is not a number
     
string = string.replace('$', '');
string = string.replace('â‚®', '');
string = string.replace(',', '');
string = string.replace(' ', '');

if(!isNaN(parseFloat(string)) && isFinite(string)){
  return parseFloat(string);
} else {
  return 0;
}
}


Mike Allen
Mega Sage

Can you do it on the server side?



Before insert



condition: current.item3_cost.changes()



current.item3_cost = current.item3_cost + 'testadjustment';