How can I display a list from an array by clicking a button or calling a function?

After incorporating a button that generates an unordered list from an array (e.g. var list_content = ["Apple", "Banana", "Orange", "Mango", "Papaya"];), each item of the array is displayed as a list item through the li element. The resulting list is appended to a designated div target.

var question4 = document.querySelector('#btn4');
question4.addEventListener('click', switch4);

var listContent = ['Apple', 'Banana', 'Orange', 'Mango', 'Papaya'];

function switch4() {
    var newElement = document.createElement('Li');
    div4.appendChild(newElement);
    for (var i = 0; i < listContent.length; i++) {
        newElement.textContent += listContent[i];
    }
}

Upon clicking the button on the webpage, the string 'AppleBananaOrangeMangoPapaya' appears after every click.

When adjusting the for loop to read:

 newElement.textContent = listContent[i];

Only 'Papaya' is then displayed.

The objective is for the button to display 'Apple', 'Banana', 'Orange', 'Mango', and 'Papaya' individually after each button press (such as 'Apple' on the first click, 'Banana' on the second click, and so on). Assistance is needed in achieving this desired functionality.

Answer №1

While looping through the entire listContent array with each button click, an issue arises. To resolve this, you can introduce an index variable with an initial value of 0. By only adding the listContent element at that index and utilizing post-increment with ++, it will consistently add the subsequent element on every click, demonstrated here:

var div4 = document.querySelector('#div4');
var question4 = document.querySelector('#btn4');
var index = 0;
question4.addEventListener('click', switch4);

var listContent = ['Apple', 'Banana', 'Orange', 'Mango', 'Papaya'];

function switch4() {
  var newElement = document.createElement('Li');
  newElement.textContent = listContent[index++];
  div4.appendChild(newElement);
}
#div4 {margin-top:10px;}
li {margin: 0 10px;padding: 5px 0;}
<button id="btn4">Click Me</button>
<div id="div4"></div>

Answer №2

Check out this code snippet:

const button = document.querySelector('#btn4');
button.addEventListener('click', toggleText);

const fruits = ['Apple', 'Banana', 'Orange', 'Mango', 'Papaya'];

let index = 0;
function toggleText() {
    const newElement = document.createElement('li');
    div.appendChild(newElement);
    newElement.textContent = fruits[index];
    index++;
    if (index >= fruits.length){
        index = 0;
    }
}

Answer №3

Issue

As you loop through the array, all items are being appended to the same li element each time you click. This results in all elements in the array being merged together and added as a new li element.

for (var i = 0; i < listContent.length; i++) {
        newElement.textContent += listContent[i]; // --> issue
    }

Resolution

To add an element with every click, it is recommended to use a variable to keep track of which elements have already been added to the list.

let startIndex = 0;
function switch4() {

    if(startIndex < listContent.length){
       let newElement = document.createElement('Li');
       div4.appendChild(newElement);
       newElement.textContent = listContent[startIndex];
      startIndex++;

    }

}

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

Detecting click events in D3 for multiple SVG elements within a single webpage

My webpage includes two SVG images inserted using D3.js. I am able to add click events to the SVGs that are directly appended to the body. However, I have encountered an issue with another "floating" div positioned above the first SVG, where I append a dif ...

Exploring methods to extract specific attributes from an array of objects stored in JSON format

I am working with an array of JSON objects. arr = [{'a'=> 1, 'b'=> 2, 'c'=> 3}, {'a'=> 4, 'b'=> 5,'c'=> 6}, {'a'=> 4, 'b'=> 5,'c'=> 6}] ...

Is there a way to determine if a radio button or checkbox has been selected?

In my HTML code, I have the following: <div id="f4" class="none"> <h4>Which tariff do you want to select?</h4> <input type="radio" name="tarif" value="tarif1" id="t1"><label for="t1">Tariff 1</label> <br&g ...

Tips for obtaining the current date in the head of a Next.js application

My goal is to utilize Date.now() within a script tag inside the head section. The code snippet I am using is as follows:- import Link from "next/link"; import Head from "next/head"; export default function IndexPage() { return ( ...

I utilized the explode function in PHP to transform a string into an array. Now, I require assistance with manipulating

Currently, I am facing a challenge where I have converted a string into an array in PHP using explode. I need to pass this array to a separate JavaScript page and then access the data values from within. Below is the structure of the array in JavaScript o ...

Quick fix for obtaining only one response

I'm facing a dilemma where I need to redirect the user to the dashboard page after they log in, but also send their JSON details to my client-side JavaScript. While I know that there can only be one res.send/end/json in a response and dynamic data can ...

Issue with default behavior of infinite scroll in Angular 4

I'm currently working on incorporating infinite scroll into my Angular 4 application. I've carefully followed all the guidelines provided on https://www.npmjs.com/package/ngx-infinite-scroll According to the documentation: By default, the dir ...

What strategies can be employed to streamline the code provided?

Can someone help simplify this JavaScript code for me? I would really appreciate it. Thank you! $(function() { $("#show1").click(function() { $("#showmore1").toggle(); }) $("#show2").click(function() { $("#showmore2").toggle(); ...

Does fetch automatically read stream data only after all chunks have been received and not immediately upon receiving each chunk?

When handling a stream response with a content-type of text/event-stream using fetch, reader, and decoder, it seems that the reader only returns after all chunks are received. I expected the reader to return as soon as each chunk is received. Am I approach ...

How can an item be added to an array only once, even if the function is called multiple

I have a scenario where I need to add a channel to an array only if its level is above a certain threshold. This function serves as the delegate callback for providing the channel level. While this function is continually used to provide level data, I spe ...

Utilize ReactJS and AJAX to easily upload images

Having trouble with uploading an image through a form to a url/api. When I submit the form, I'm calling the handleImgUpload() method. The issue is that the request being sent is coming back empty. Seems like there might be a problem with new FormData ...

Compose a tweet using programming language for Twitter

How can I send a message to a Twitter user from my .NET application? Are there any APIs or JavaScript code that can help with this task? Any assistance would be greatly appreciated. ...

Pointer Functions

Currently tackling a problem that involves finding the number of times an element in an array is equal to the average of its neighbors. However, I've encountered a baffling error that's causing me quite the headache. #include<stdlib.h> #in ...

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...

Purging a Collection

I have a pretty straightforward setup using Wordpress Advanced Custom Fields. I want to enhance my custom posts by adding additional fields and displaying them on the post page. The current code I have works well, but when it comes to a custom field with m ...

What makes JSON in string form a legitimate string?

We all know that we can't use double quotes within double quotes: var str = ""hello""; //this will result in an invalid string However, when I stringify an object like this var obj = {"name":"abc"} var str = JSON.stringify(obj). str // outputs "{"n ...

Creating a callback function within its own definition

I need help with my download function that is calling a callback to "downloadCallback". Is it possible to define the downloadCallback function inside the download function itself? If so, how can I achieve this? Below is the implementation of the download ...

Initialization of webix combo options values in HTML code

Currently, I am working with the Webix UI framework and I am trying to achieve something similar to: <div view="combo" options="fruit"></div> This is what I have in my JavaScript file: $scope.fruit =[{id:1, value: "Apple"}, {id:2, value: "Ba ...

TinyMCE is deleting Bold tags in a numbered list when saving a form

I recently integrated the tinymce editor into one of my textareas, allowing users to format their text with options like bold, underline, and italic. Here is the implementation code: tinymce.init({ branding: false, statusbar: false, resize:true ...

Unveiling the mystery: Locating the position of an element within a multidimensional array using JavaScript or JQuery

How can I retrieve the index of a specific element in a JSON array converted from a PHP array using json_encode, using JavaScript or JQuery? Initially, the user will choose an option where the values correspond to people's IDs. <select class="for ...