Push local variable to global array?

I’m stuck on something that seems really basic but I haven’t been able to find a solution. This is what my code setup looks like:

var myArray = [1,2,3];


My goal is that every time someone submits on #submitButton, a new value of “4” is pushed to the myArray. The console log within the function shows [1,2,3,4] but it doesn’t continue to add to the array, it overwrites the previous pushed value whenever the function is run. It also isn’t affecting the global array at all. Is it possible to do what I’m trying to do here?

It should be:

var myArray = [1,2,3];


Notice the parentheses after function.

Hey @jk0609

I’m not entirely sure what the problem is but just a suggestion:
Is it possible that your syntax is affecting the function, it looks like you are missing a closing parenthesis after function, it should looks something like this:

$('#submitButton').submit(function() {

Not sure if that helps at all.

Edit @BenGitter beat me too it, his code example looks much prettier haha

Well not really, I forgot a parenthesis myself :blush:

You need to use triple backticks to post code to the forum.
See this post for details.

Crap, sorry for the confusion. I was trying to emulate the code and the missing parenthesis is in place, I just missed it in my post. My actual code is here:

var streamArr = ["ESL_SC2", "OgamingSC2", "bmkibler"];

});//document ready

Edit: document.ready is closed properly, I just missed the highlight for copy/paste.

No worries @jk0609 ,

.value isn’t a valid method. Swap out .value for .val()

see if that does the trick.

I feel form somewhere in HTML, and what does form submit do?

1 Like

Hey @ollyhub,

#addStreamField’ is a text input field, so .value is grabbing whatever the user is typing into the text box based on:

The function itself is doing what I want it to do, I just can’t export any of the results out to a global array. Any ideas?

Does submitting the form refresh the page?

It seems to yeah, all the elements are reloading.

To prevent reloading on submit:

$("#addForm").submit (function (event) {
 event.preventDefault ();

 /* your code.. */


Ah that’s it then. If it refreshes the JS restarts as well. Which means that myArray will be set to [1,2,3] again.

I believe e.preventDefault() should work. You will have to add e as a parameter to your anonymous function:


Haven’t tested it…

@BenGitter @NeckersBOX

That did it. Thanks a bunch, I never would have figured that out. Cheers!