What is the best way to refresh the innerHTML of a div using the values from a JavaScript array when new elements are added to it?

I currently have an array with three items, along with four buttons - each designed to add a new item to the array.

Although the process of adding items into the array using the buttons is successful, I am facing an issue with the display within the div element. The first item I add appears correctly in the div, but after that, whenever I click on any of the remaining buttons, the same item keeps showing up.

What could be causing this problem? Any suggestions?

JSFiddle

var inventory = ["Apple", "Pear", "Orange"];

for (i = 0; i < inventory.length; i++)
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";

function addItem(newItem, itemBtn) {
  inventory.push(newItem);
  document.getElementById(itemBtn).style.display = "none";
  console.log(inventory);
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";
}
<p>Fruits:</p>
<div id="arrayDiv"></div>
<hr>
<input id="banana" type="button" value="Banana" onclick="addItem('Banana', 'banana')">
<input id="melon" type="button" value="Melon" onclick="addItem('Melon', 'melon')">
<input id="pineapple" type="button" value="Pineapple" onclick="addItem('Pineapple', 'pineapple')">
<input id="coconut" type="button" value="Coconut" onclick="addItem('Coconut', 'coconut')">

Answer №1

inventory[i] when the loop is executed, i is set to a specific value which remains constant.

Once the loop displays ["Apple", "Pear", "Orange"], the value of i becomes fixed at 3.

(Apple => 0, Pear => 1, Orange => 2), so the next value for i will be 3 because of i++ in the for loop.

This could result in displaying the same Fruit name multiple times in HTML.

To prevent this issue, use newItem instead of inventory[i].

var inventory = ["Apple", "Pear", "Orange"];

for (i = 0; i < inventory.length; i++)
  document.getElementById("arrayDiv").innerHTML += inventory[i] + "<br>";

function addItem(newItem, itemBtn) {
   
  inventory.push(newItem);
  document.getElementById(itemBtn).style.display = "none";
  
  document.getElementById("arrayDiv").innerHTML += newItem + "<br>";
}
<p>Fruits:</p>
<div id="arrayDiv"></div>
<hr>
<input id="banana" type="button" value="Banana" onclick="addItem('Banana', 'banana')">
<input id="melon" type="button" value="Melon" onclick="addItem('Melon', 'melon')">
<input id="pineapple" type="button" value="Pineapple" onclick="addItem('Pineapple', 'pineapple')">
<input id="coconut" type="button" value="Coconut" onclick="addItem('Coconut', 'coconut')">

Answer №2

The value of i remains constant as the loop was only executed with an initial array length of 3;

To find the last index, you can modify the code like this:

function addToInventory(item, buttonId) {
   inventory.push(item);
   document.getElementById(buttonId).style.display = "none";
   var lastIndex = inventory.length - 1;
   document.getElementById("arrayContainer").innerHTML += inventory[lastIndex] + "<br>";
}

Answer №3

For you, the index i functions on a global level. So, when your loop initially ran, it stopped at 3 and continued to do so from that point onward. Consequently, any new additions will consistently be placed at index 3 in the array. The array itself will update correctly despite this reliance on the i value.

While other answers may offer alternative solutions, one method you can explore involves utilizing a Document Fragment and reducing dependence on innerHTML, favoring more DOM APIs such as .append and createTextNode.

This particular approach is beneficial due to the fact that the number of HTML nodes displayed is directly related to the content within inventory. Therefore, renderInventory will consistently operate based on inventory (as the single source of truth).

var inventory = ["Apple", "Pear", "Orange"];

function renderInventory(){
  document.getElementById("arrayDiv").innerHTML = '';
  const df = document.createDocumentFragment();
  for (let i = 0; i < inventory.length; i++)
  {
     const textNode = document.createTextNode(`${inventory[i]}\n`);
     df.append(textNode);
  }
  document.getElementById("arrayDiv").append(df);
}

function addItem(newItem, itemBtn) {
  inventory.push(newItem);
  document.getElementById(itemBtn).style.display = "none";
  renderInventory();
}
#arrayDiv{
white-space:pre
}
<p>Fruits:</p>
<div id="arrayDiv"></div>
<hr>
<input id="banana" type="button" value="Banana" onclick="addItem('Banana', 'banana')">
<input id="melon" type="button" value="Melon" onclick="addItem('Melon', 'melon')">
<input id="pineapple" type="button" value="Pineapple" onclick="addItem('Pineapple', 'pineapple')">
<input id="coconut" type="button" value="Coconut" onclick="addItem('Coconut', 'coconut')">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to include various reactions at once?

I've been searching everywhere for solutions but I'm stuck on this issue. Here's the scenario I'm dealing with: I need my bot to execute a command that will send an embed to a specific channel accessible only by admins. Done. Fol ...

Unfortunately unable to retrieve data with Meteo HTTP call

I've encountered a peculiar issue with meteor. I'm attempting to perform an HTTP call and utilize the retrieved data in a React component, but I'm unable to access the data returned. On the server: 'get': function get() { try ...

Uploading files using Ajax in the Laravel framework

I am attempting to utilize ajax to upload a file in Laravel. $("#stepbutton2").click(function(){ var uploadFile = document.getElementById("largeImage"); if( ""==uploadFile.value){ } else{ v ...

Tips for preventing the collapse of a table row using a button?

I have implemented a Bootstrap collapse feature on my table row. Currently, the collapse can be triggered by clicking anywhere on the row, which is working as intended. However, I would like to make one exception - if the user clicks on the desktop icon i ...

JavaScript Document Object Model: Locate an element with a class that is either similar to or includes a specific substring

I am facing a situation where I need to locate a wrapper element with a specific class name that includes a random id, such as wp-rgtayfu-fxyjzw-wrapper. The class will always have the substring wrapper in it, and there is only one element in the document ...

Using reduce in JavaScript to form a fresh object

I've been struggling with creating an object using reduce from a nested array. The task is to generate a new object with keys named _uid and values matching the initialValue from the objects that contain both properties. I have written a function that ...

Integrate a variable called "counter" with the jQuery ID

I currently have the following code, which is functioning well. $('.clickable').click(function(e){ e.preventDefault(); $('#toggle').slideToggle(); }); $('.clickable1').click(function(e){ e.preventDefault(); $('# ...

Componentizing Vue for Better Reusability

Currently tackling a large application filled with legacy code, I'm facing a repetitive issue that has popped up twice already. It's becoming clear to me that there must be a more efficient way to solve this problem. Here's what I'm dea ...

Retrieve the href value from a DOM element

I'm currently working on a piece of code that aims to extract only the hrefs from the nav section. Here's what I have so far: componentDidMount(){ $("nav ul li a").each(function(k, j){ console.log(j); }); } So far, I've bee ...

Creating a module within a component in angular - step by step guide

I am interested in dynamically creating a component inside another component. This will allow me to pass my dynamic HTML template directly to the decorator like this: //code /** * @param template is the HTML template * @param container is @ViewChild(& ...

React-Enabled Chat Engine API for Seamless Customer Support

Chat Engine io is the API I am currently working with. It allows you to integrate chat rooms into your application. I have developed an application with a support chat feature where the admin can communicate with users by entering their email. Despite mul ...

Exclude child rows from row count in DataTable

I have successfully implemented a feature on my datatable where child rows are toggled when a parent row is clicked. Here is the code I used: $(function() { $('tr.parent') .css("cursor","pointer") .attr("title","Click to expa ...

Ways to expand the constructor function of the THREE.Mesh class

Exploring Three.js, I'm working on creating a basic model of the solar system. My current task involves building constructor functions for planets and moons. However, I keep encountering an error message: The function setShadow() is not recognized. ...

Get the Zip file content using PushStreamContent JavaScript

I am looking for the correct method to download a PushStreamContent within a Post request. I have already set up the backend request like this: private static HttpClient Client { get; } = new HttpClient(); public HttpResponseMessage Get() { var filenames ...

Looking for guidance and bug assistance in HTML and JS, possibly involving PHP and MySQL. Can anyone offer advice?

I'm attempting to create an auto-complete feature for a forum (similar to the tags below) that will function within LimeSurvey. I am fairly new to this, so please provide explanations as if you were explaining it to a 5-year-old :) My objectives are: ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

How to change a string from utf-8 to iso-8859-1 using Javascript

Although it may seem unpleasant, it is essential. I am facing an issue with a HTML form on my website that uses utf-8 charset but is sent to a server operating with iso-8859-1 charset. The problem arises when the server fails to interpret characters commo ...

My array magically transforms into an object once it reaches 22 elements, why is that happening? (node)

While working on a form with multiple checkboxes that have the same name and submitting it through a node/express post route, I encountered an issue. Here is the corresponding HTML code: https://pastebin.com/xeQae6GA The problem arises when trying to ret ...

Utilize or Bring in an external JavaScript file within Ionic 2

Currently working with Ionic 2 and Typescript Angular 2 and facing an issue. I need to utilize an external JavaScript file located at . How can I import or include this in my project? ...

compress a website to display advertisement

Here is a JSFiddle link I would like to share with you: I am currently working on squeezing the webpage to display an ad on the right side. http://jsfiddle.net/5o6ghf9d/1/ It works well on desktop browsers, but I am facing issues with iPad Safari/Chrome ...