Link to home
Start Free TrialLog in
Avatar of oggiemc
oggiemcFlag for Ireland

asked on

Javascript onClick function initialisation

Hello all,

I have a dialog button which when clicked executes a function..The first time, this button is clicked i want to initialise a bunch of variables, but each subsequent time the variables should change i.e increment..The only way i can think of implementing this is using the typeof operator and testing for variable existence, as  is done in the code attached. Can someone tell me whether this is bad practice or whether there is a better way of doing this??

Thanks
onClick: function () {

    if (typeof count === 'undefined') {
        count = 0; 
    } else {
        count++;
    }

    if (typeof selectOptionArry === 'undefined') {
        selectOptionArry = new Array(); // Define array that contains what element option was selected in the dialog e.g input, textarea, table etc
    }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oggiemc

ASKER

So, i assume what your saying is:

var count;

if (count) {

if (selectOptionArry) {                                  ???

The problem here is when the function exits, count is 'undefined' again.. And so each time the button is clicked, it will be set as 'undefined'..

If that is what you are asking me to do??


No, I did not said to add :
var count;
Avatar of oggiemc

ASKER

sorry..

if (count){
count++;
}
else{
var count;
}
Avatar of oggiemc

ASKER

if (count){
count++;
}
else{
var count = 0;
}
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oggiemc

ASKER

Ok,

If i just have:

if(count){
}

I get an error : count is not defined

???
Avatar of oggiemc

ASKER

Just after seeing your last comment..the problem is, even if i declare count outside the onClick function, the dialog that contains the onClick function exits at the same time as the onClick function exits and so the var count will keep resetting..
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of oggiemc

ASKER

Ok, got it working now thanks.. Points coming ur way..