Adding Array Elements to List Elements

I am facing an issue while trying to display an array of items in a list. The problem is that when I click submit, it adds all the array items to each list item instead of adding one item each time.

Here is the link to JSFIDDLE: https://jsfiddle.net/b7Lwbrof/

Thank you!

var itemList = [];
var container = document.getElementById('container');

// On click
document.getElementById('submit').addEventListener("click", function(){
    var itemValue = document.getElementById('itemValue').value;

    // Push to array
    itemList.push(itemValue);

    // Append to List
    for(i=0; i<itemList.length; i++) {
        var items = document.createElement("li");
        document.getElementById('container').appendChild(items);
        items.innerHTML = itemList[i];
    }
})

Answer №1

To avoid using a loop, simply add the item after it has been pushed to the itemList.

document.getElementById('submit').addEventListener("click", function(){
    var itemValue = document.getElementById('itemValue').value;

    // Push the value to the array
    itemList.push(itemValue);

    // Add the item to the list
     var listItem = document.createElement("li");
     document.getElementById('container').appendChild(listItem);
     listItem.innerHTML = itemList[itemList.length-1];
})

Answer №2

items.innerHTML = itemList[itemList.length - 1] // retrieve the last item

instead of

items.innerHTML = itemList[i]

Make sure to eliminate the loop as per @digit's suggestion.

Check out the Fiddle here.

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

Troubleshooting: The Jquery each loop is malfunctioning

I am new to using jquery and I have encountered a problem in my project. I am attempting to iterate through all the links within the #rate_box and attach a click event to them. This click event is supposed to send data to an external php script, then remov ...

Modifying Props in Reactjs: Ways to update data passed from parent component to child component

Currently, I am working on a project where I have multiple components on a page and pass data between them using props. The issue arises when I update the data in the parent component but the child component still uses the old data. Let me illustrate with ...

Customizing the display field in an ExtJs Combobox

I am working on a java web application that utilizes an entity class to populate a combobox with ExtJs. The issue I am facing is as follows: Some entries in the displayField may contain html code. To prevent any issues, I used flexjson.HTMLEncoder during ...

Tips for navigating to a specific row within a designated page using the Angular Material table

Utilizing angular material, I have set up a table with pagination for displaying data. When a user clicks on a row, they are redirected to another page. To return to the table page, they must click on a button. The issue arises when the user needs to retu ...

My intention is to ensure that the page is printed with the Background graphics checkbox pre-checked

When using the print button, I typically include the following code: onclick="window.print();" I also came across this code snippet to set a checkbox as checked by default: <style type="text/css" media="print"> * { -webkit-print-color- ...

Link-defying button

I'm developing a website with a homepage that serves as an entry point to the rest of the site (it welcomes the user and allows them to click anywhere to access the main website). The following code accomplishes this: <template> <div onc ...

Generate a Calendar Table using JavaScript in the Document Object Model (DOM

I have set up a table with 6 rows and 5 columns. The purpose of the table is to represent each month, which may have varying numbers of days. I want each column to display dates ranging from 1-30 or 1-31, depending on the specific month. Here's what ...

Is it possible to fulfill a promise within an if statement?

I'm fairly new to using promises in JavaScript, and I am currently facing an issue where a function needs to execute before running some additional code in another function. The problem arises when the promised function includes an if statement that l ...

Delete the entry with the specified unique identifier "this text" from the MongoDB database

So, I've been searching high and low but still can't seem to figure out how to get this to work. Here's the issue I'm facing: I'm currently working on a chat application using node/express/socketio, and I'm attempting to crea ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

Take action upon window.open

I have a code snippet here that opens a window. Is it possible to make an ajax call when this window is opened? window.open("http://www.google.com"); For instance, can I trigger the following ajax call once the window is open: var signalz = '1&apos ...

Testing event emitters in node.js: a step-by-step guide

Imagine the scenario where I need to create a basic task. However, I also need to develop a test that validates the following criteria: The task should emit an object. The emitted object must have a property named "name". I am utilizing mocha and chai e ...

Having trouble retrieving the API URL id from a different API data source

For a small React project I was working on, I encountered a scenario where I needed to utilize an ID from one API call in subsequent API calls. Although I had access to the data from the initial call, I struggled with incorporating it into the second call. ...

What is the proper way to create a regex pattern that specifies 'without any spaces'?

I need assistance in creating a regex expression that specifies "and NO whitespaces". I have to incorporate this into the following if statement shown below: $('#postcode').blur(function(){ var postcode = $(this), val = postcode.val(); ...

Tips for avoiding unnecessary re-renders in React JS to halt additional API requests:

Presented here is a main component (Cart) and a subordinate component (CartItem). Within the main component, there exists a button that relies on the state, which changes through the checkAvailability function passed down to the child via props. import {u ...

text field remaining populated

I have a form where the input fields clear when they are clicked on. It works well on most pages, but there is a specific type of page where it is not functioning properly due to the presence of another javascript running. - issue observed // On this pa ...

Steps for converting the current JSON_OBJECT into a list format

Struggling to grasp how I can swap results in my query. This code interacts with an Oracle database: TO_NCLOB(JSON_OBJECT( 'name' VALUE TRIM(tb1.DS_NAME), 'birth' VALUE tb2.DT_BIRTH, 'id' V ...

Why is the child's CSS hover not functioning when the body has an event listener attached to it?

Check out the repository link here: https://codepen.io/Jaycethanks/pen/WNJqdWB I am trying to achieve a parallax effect on the body and image container, as well as a scale-up effect on images when hovered over. However, the hover functionality is not work ...

No data returned from Ajax GET request

Utilizing Ajax with JavaScript, I am processing data on a PHP page using the GET method. Is it possible to send data from the PHP page when the GET query is empty? My goal is to have a live search feature that filters results based on user input. When a us ...

Creating a file logging system with console.log() in hapi.js

I have recently developed an Application with Hapi.js and have utilized good-file to record logs into a file. However, I am facing an issue where the logs are only written to the file when using request.log() and server.log() methods. My goal is to also lo ...