1

I want to store my input values into an array.

When i click enter i get the input value and push into vals array.

Then i console log but whenever i click enter, it only push last input value.

Why?

JSFIDDLE

var input = document.getElementById("input");

input.addEventListener("keyup", function(e) {
  var val = e.target.value;
  var vals = [];

  if (e.which == 13) {

    vals.push(val);
    input.value = " ";
    console.log(vals);

  }

}, false);
1
  • 2
    Because you re-declare vals everytime the keyup listener is executed. Move it out of that listener. Commented Feb 21, 2017 at 12:42

3 Answers 3

1

the reason why your code is only displaying the last value is because your array is local to the function hence it only exists while that function is in scope. Rather make it global, that way you can push more than one element into the array and later access it.

 var vals = [];   //make this global 

 var input = document.getElementById("input");

input.addEventListener("keyup", function(e) {
  var val = e.target.value;
  if (e.which == 13) {

    vals.push(val);
    input.value = " ";
    console.log(vals);

  }

}, false);
Sign up to request clarification or add additional context in comments.

Comments

0

You need to initialize your array only once

var input = document.getElementById("input");
var vals = [];
input.addEventListener("keyup", function(e) {
  var val = e.target.value;


  if (e.which == 13) {

    vals.push(val);
    input.value = " ";
    console.log(vals);

  }

}, false);

Comments

0

Declare the vals array outside of the event listener

var input = document.getElementById("input");
var vals = [];

input.addEventListener("keyup", function(e) {
    var val = e.target.value;

    if (e.which == 13) {

        vals.push(val);
        input.value = " ";
        console.log(vals);

    }

}, false);

Comments

Your Answer

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