Kasador
Kasador

Reputation: 429

Pushing values into an empty array?

I'm recently new at programming and JavaScript. I'm not sure why this doesn't work. I'm trying to insert numbers into an empty array. And then have them displayed into the div with the id of "value".

My JavaScript:

var array = new Array();
// var array = [];

$(document).ready(function() {
  $('#btn').on('click', function() {
    var $input = $('#input').val();
    array.push($input);
  });
  $('#value').text(array);
  console.log(array);
});

My HTML:

<div id="number">
  <input type="text" id="input">
  <button id="btn"> Submit </button>
</div>

Upvotes: 1

Views: 7842

Answers (2)

Twisty
Twisty

Reputation: 30883

Just a reminder that Input Fields supply a String not an Integer.

Take a look:

var myArray = [];

$(function() {
  $('#btn').on('click', function() {
    var $input = $('#input').val();
    myArray.push(parseInt($input));
    console.log(myArray)
    $('#value').text("[" + myArray.join(", ") + "]");
  });
});
.input {
  padding: 10px;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 1em;
}

.input input {
  width: 60px;
  height: 1.25em;
}

.input button {
  padding: .25em .6em;
}

.output {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input">
  <input type="number" id="input" /> <button id="btn">Add</button>
</div>
<div class="output">
  <div id="value"></div>
</div>

Upvotes: 2

Ori Drori
Ori Drori

Reputation: 191976

You render the empty array once, when the document is ready. Adding more items to the array doesn't rerender the DOM with the new items. You need to update the DOM on each click by moving $('#value').text(array); into the click event handler:

var array = new Array();
// var array = [];

$(document).ready(function() {
  var $input = $('#input');
  var $value = $('#value');

  $('#btn').on('click', function() {
    var val = $input.val();
    array.push(val);
    
    $value.text(array);
    console.log(array);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input">
<button id="btn">Add</button>
<div id="value"></div>

Upvotes: 3

Related Questions