Sean Cunningham
Sean Cunningham

Reputation: 3106

Any way to access a variable name from outside a function as a parameter of the function?

I've got a simple JavaScript function which allows visitors to dynamically add input fields to a form. In some cases I'll need to call this function several times on a page and I'm trying to simplify things by only creating one function and passing the necessary parameters to it.

My sticking point is that I need to have a counter for each category of input that I'm creating so that I can add/remove inputs as needed. Here's what I've got so far:

var assigneeCounter = 1;
var uploadCounter = 1;


function addInput(fieldlabel, inputclasses, inputCounterID, inputCounter){
  alert(inputCounter);
}

The HTML to call this function is as follows:

<a href="javascript:addInput('Assignee','required-text', 'assignees', 'assigneeCounter');">Add Another Assignee</a>
<a href="javascript:addInput('File Uploads','', 'uploads', 'uploadCounter');">Add Another File Upload</a>

My goal is to have the function call look for the specific variable that relates to it (e.g. assigneeCounter for the Assignees inputs, uploadCounter for the Uploads, etc.). However, when I alert that variable it simply writes "assigneeCounter" instead of "1".

I'm sure I'm just missing something fundamental about variable scope here and I'm no JavaScript expert so I figured I'd ask those who are.

Thanks in advance!

Upvotes: 1

Views: 68

Answers (2)

nneonneo
nneonneo

Reputation: 179422

Yes. If those variables are at global scope, you can access them through the window object:

window[inputCounter];

See Use dynamic variable names in JavaScript for more details on how this works.

Upvotes: 1

Jay
Jay

Reputation: 3305

You can access it like this:

alert(window[inputCounter]);

Upvotes: 1

Related Questions