Javascript onClick function initialisation

oggiemc
oggiemc used Ask the Experts™
on
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

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Multitechnician
Top Expert 2014
Commented:
if (count) {

if (selectOptionArry) {

Author

Commented:
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??


leakim971Multitechnician
Top Expert 2014

Commented:
No, I did not said to add :
var count;

Author

Commented:
sorry..

if (count){
count++;
}
else{
var count;
}

Author

Commented:
if (count){
count++;
}
else{
var count = 0;
}
leakim971Multitechnician
Top Expert 2014
Commented:
you need to declare you variable outside your onclick function
(and yes with var count = null;)

Author

Commented:
Ok,

If i just have:

if(count){
}

I get an error : count is not defined

???

Author

Commented:
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..
leakim971Multitechnician
Top Expert 2014
Commented:
it depend where you put the "count" variable

Author

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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial