Skip to content
Advertisement

How can I fill an empty JavaScript array?

I’ve looked all over online for something that could aid me to fill an empty array with given values the user inputs from a text box that will get stored inside an array.

So far I have the following code:

var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
  var x = [];
  x.push(text);


  console.log(x);

When I input something in the textbox and see what happens in the console it tends to replace the previous value that was sent there first.

For example, if I wrote “Hello”, this will get sent into the array so it’ll be seen as:

["Hello"]

But if I type in something again, hoping that the result will continue to store the data being inputted inside, it does this:

*Writes down “Hi” in the text box:

["Hi"]

I want the result to be something like this:

["Hello", "Hi"]

I am aware my code does need tweaking and I am doing something wrong which is causing that result, but I can’t seem to figure it out.

I’m looking for an answer in vanilla JavaScript.

Thank you.

Advertisement

Answer

The problem is you are redeclaring variable x and initializing it with an empty array, every time when you run that code. Make the x a global variable by moving it out of the current function or block

var x = [];

Another Block

var text = document.getElementById("input").value;
var message = document.getElementById("text-here");
message.innerHTML += text + " " + "<br />" + "<br />";
x.push(text);
console.log(x);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement