Expand my Community achievements bar.

Lifetime of variables

Avatar

Former Community Member

Trying to create an autonumber field - just need a set of unique names.

Have a function in a script object that does the creation with the autoNumner variable located at the top of the script object outside of the function and starts off as null.

form1.#variables[0].Misc - (JavaScript, client)
var autoNumber = null;

function generateNewBldgNumber ()
{
   var BldgNumber = null;
   if (null == autoNumber)
   {
      autoNumber = "1";
   }

   BldgNumber = "N_" + autoNumber; 
   autoNumber = (autoNumber * 1) + 1;
   return BldgNumber;
}

If I add a set of entries that call this in a row, it works.  If I delete one or more, the autonumber starts off at 1 again.

I am confused about why it works some of the time.

Thanks in advance.

Patrick

6 Replies

Avatar

Level 10

Did you try to add the Global Variables by going to File Menu -> Form Properties and select the Variables tab.

Global Variables can keep the value through out the form is opened.

You can access the Global variable by "VariableName.value".

Thanks

Srini

Avatar

Former Community Member

Tried it this moring, the first go round was coming out N_1, N_11, N_111 rather than N_1, N_2, N_3.

Global variables seem to want to be text, and tried to cast the text as a number without luck.

var BldgNumber = null;

BldgNumber

= "N_" + autoNumber.value;

autoNumber

= autoNumber.value + 1;

return BldgNumber;

Avatar

Level 10

You need to use the parseInt function in Javascript to convert the text to integer before incrementing the value. Also you always need to use ".value" to access the Global variable value.

var BldgNumber = null;

BldgNumber = "N_" + autoNumber.value;

autoNumber.value = parseInt(autoNumber.value) + 1;

return BldgNumber;

Thanks

Srini

Avatar

Former Community Member

autoNumber.value

= 1 + parseInt (autoNumber.value);

Doesn't do the adding.

So, I am drawing a blank on why it isn't working,

Thanks,

Patrick

Avatar

Level 10

Sorry I missed one more step in between.

You need to convert the incremented value to string before you assign it to the Global variable.

var BldgNumber = null;

//Increment the Global Variable.

var intNumber = parseInt(autoNumber.value) + 1;

//Assign the incremented value to Building Number

BldgNumber = "N_" + intNumber;

//Convert the incremented value to String and assign back to the Global Variable.

autoNumber.value = intNumber.toString();

return BldgNumber;

Thanks

Srini

Avatar

Former Community Member

Got it to work.  We forgot to turn the integer back into a string.


i = parseInt(autoNumber.value);
i++;
autoNumber.value = i.toString (10);

Thanks,

Patrick