1

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>
4
  • Which part isn't "doesn't work"? Commented Mar 29, 2018 at 22:11
  • Show your html too Commented Mar 29, 2018 at 22:12
  • Move $('#value).text(array) inside the click handler. Commented Mar 29, 2018 at 22:12
  • @JaredSmith Thank you so much! I realized that it just loaded once and I need to have it updated after each time I insert a new value. By moving it into my click handler did the trick. Thanks a lot! <3 Commented Mar 29, 2018 at 22:18

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.