1

I'm trying to build an array in javascript that contains a list of ids. Here is a simplified version of the function that I have...

function updateCost(id) {
    var inputArray = [];
    inputArray.push(id);
}

And here is the html code...

<input type="file" name="field1" id="field1" onchange="updateCost('1');" />
<input type="file" name="field2" id="field2" onchange="updateCost('2');" />
<input type="file" name="field3" id="field3" onchange="updateCost('3');" />
...

What I would like to happen, is each time I select a file from my computer using one of the file input fields that I have, I would like the id of that input field to be stored in the inputArray array. However, every time I select a file, it adds that id to the array, but it doesn't append it to the array, so everything else in the array is deleted, leaving only one entry in the array.

Is there any way to make the array data persistent so it will grow each time I use one of the of the file input fields?

Thanks!

2 Answers 2

4
(function() {


   var inputArray = [];
   function updateCost(id) {
    inputArray.push(id);
   }


})();

Define it outside the scope of the function. You don't really need the enclosing anon function around, that's just my personal style.

Sign up to request clarification or add additional context in comments.

3 Comments

@lewisqic: consider accepting the answer if it's what you were looking for.
But if updateCost is defined within an anonymous function, it will be undefined when the change event is fired, at least in browsers that don't suck. updateCost needs to be global.
That's true, which is why I'd advise unobtrusive JS.
0
function updateCost(id) {
    if(typeof updateCost.inputArray=="undefined")updateCost.inputArray=[]
    updateCost.inputArray.push(id);
}

Make Array is "Static"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.