0

I want that when I press the submit button it adds a value to the array but instead it keeps returning the same value.

$(document).ready(function(){
    if(typeof arr == "undefined"){
        var arr = new Array();
    }

    arr.push(2);
    $("#submit").click(function(){
       console.log(arr);
    });
});

I want it to add a 2 each time I press submit like this: First press

[2]

Second press

[2, 2]

But now the array just stays 2 as if it just refreshes.

  • 2
    If you want something to happen when you click the button, isn't it obvious that it has to be in the `click()` function? – Barmar Nov 12 '13 at 11:44
  • Oh right sorry that's so stupid.. –  Nov 12 '13 at 11:46
  • 2
    As a side note, it's recommended to use `var arr = []` instead of `new Array` http://stackoverflow.com/questions/7375120/why-is-arr-faster-than-arr-new-array – Ionuț Staicu Nov 12 '13 at 11:49

4 Answers4

4

Your push is inside DOMReady. It is only ever called once. Did you mean to call it inside the #submit click listener?

Or does the #submit click actually submit a form so that you end up reloading the page, and you expect DOMReady to append to the existing array? In that case, no, it doesn't work that way, javascript variables aren't persistent across page refreshes (unless you store them in something like a cookie or localStorage)

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
3

You should call push() inside your click() event to make it run on every click:

$(document).ready(function(){
    if(typeof arr == "undefined"){
        var arr = new Array();
    }

    $("#submit").click(function(){
       arr.push(2);
       console.log(arr);
    });
});
Nasser Torabzade
  • 6,490
  • 8
  • 27
  • 36
-1

Your problem is that the page does not know of any previous values, when you click the button you need to submit it to a server/save in storage (cookie/localStorage/etc), and on page load you should retrieve those values again, that way the array will persist across page reloads

epoch
  • 16,396
  • 4
  • 43
  • 71
-1

Try this

 $("#submit").click(function(){
    arr.push(2);
    console.log(arr);
        $.each(arr, function(index, newArr){
           // console.log(newArr);
        });
    });
Avinash Ware
  • 158
  • 11