简体   繁体   中英

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>

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM