Adding elements to an array when a div is clicked

I am attempting to display an array containing the IDs of div elements when a user clicks on one of the divs. However, my current code keeps replacing the existing values in the array instead of adding to it. As a result, I only get one, two, or three as outputs, rather than one,two,three as desired. I suspect that the issue lies with how I am using the click function, but I'm not entirely certain.

<div class="status" id="one">1</div>
<div class="status" id="three">333</div>
<div class="status" id="two">22</div>

<p id="demo">The array.</p>

$('.status').click(function() {
    var status = $(this).attr('id');
    var list = []; 
    list.push(status)
    //alert(status); 

    var x=document.getElementById("demo");
    x.innerHTML=list;
});

Here's a Fiddle for you to test: http://jsfiddle.net/3zDZC/

Answer №1

The issue lies in constantly recreating the array. It is best practice to define the array outside of the event handler function.

Furthermore, rather than directly setting the innerHTML property with the array, it is recommended to utilize the join method on the array. This way, the contents of the div will display the elements stored within the array.

var itemList = [];
$('.trigger').click(function() {
    var item = $(this).attr('id');
    
    itemList.push(item);
    
    var element = document.getElementById("output");
    element.innerHTML = itemList.join(', ');
});

Answer №2

Make sure to avoid clearing the array on each click event. It's better to move var list = []; outside of the click handler function:

var list = [];
$('.status').click(function () {
    var status = $(this).attr('id');
    list.push(status)
    //alert(status); 
    $('#demo').html(list);
});

Check out this jsFiddle example

Also, leveraging jQuery allows you to simplify this code snippet:

$('#demo').html(list);

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 retrieve the JSON url from the input box

My goal is to retrieve a JSON file from a URL entered in a text box. I have identified the text box as txtr and used jQuery to get the value like this: var txtbval = $("#txtr").val();. I then included this value in the JSON parsing script as follows: url: ...

Is the popup not opening with just one click?

https://i.stack.imgur.com/09dcf.png Upon clicking the first input cell, the popup opens and closes as expected. However, when closing the initial input and opening another one, an orange mark icon appears but the popup doesn't open until the second c ...

The setInterval function in JavaScript fails to update the result

I have successfully implemented a countdown function that is working as expected. // Set the date we're counting down to var countDownDate = new Date("<?= $stop_datejs ?>"); // Update the count down every 1 second var x ...

Iterate through several table data cells, extract various data points, and populate an array

I am facing a challenge with two tables on my webpage. The second table is dynamically populated with HTML using JavaScript. To accomplish this, I am checking if the <tr> tags inside the tbody are empty by using the following code: var rowCount = $( ...

Leveraging the power of Javascript's ajax capabilities to trigger PHP

When working with localization in JavaScript, I have encountered an issue where localization strings are stored in a php file and the get_string() function is used to retrieve the localized values in PHP. Specifically, I have created a script named alertpo ...

Is the function failing to detect the updated variable because it is not declared as a global variable?

I have created a quiz with 7 select boxes and a submit button, aiming to display a warning error if the select boxes are not changed or show the score if they are changed. I initialized a variable called 'changed' as false. When a select box is ...

Tips for Condensing a List of OR || Operators within a Google Apps Script

To add background colors to all columns of a Google Sheets sheet when manually entering a value in a cell, I adapted the GAS script shared by ziganotschka. However, I'm looking for a way to simplify this using an array instead of multiple || OR statem ...

What is the method behind the magic of `print(*range(*b'e'))` counting from 0 to 100?

Could someone provide insight into the process by which this code generates numbers from 0 to 100? [Code] print(*range(*b'e')) [Result] 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 3 ...

Display information from a .js file onto an HTML webpage

I'm completely new to the world of server-side development and I'm attempting to navigate it on my own. Currently, I have a server written in JavaScript using Express and I'm trying to display some content on my HTML page that was sent from ...

Is there a way to retrieve breaks and white spaces from a database in React JS with the help of Laravel?

Hello, Stack Overflow! I'm having trouble saving text from a textarea to the database. How can I preserve line breaks and spaces when retrieving the text from the database? Thank you for your help and guidance. Below is the frontend code for the t ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Invoke a function using the output of a different function

There is a function whose name is stored in the value of another function, and I need to invoke this function using the other one. The function I need to call is popup() random() = 'popup()' if ($.cookie('optin-page')) { } I attemp ...

Designing interactive elements that conceal individual paragraphs

I am working on a project that involves 3 buttons and 3 paragraphs. My goal is to create a JavaScript function that will hide all paragraphs except the one with the same letter as the button clicked. I want to achieve this by applying a CSS rule that adds ...

Configure the input to accept integer values

This page that I have developed is designed for entering Latitude and Longitude values. <div class="container "> <form class="entry"> <div class="aligncenter"> <h5 style="color:MediumTurquoise; font ...

NodeJS Request Body Not Populated

Currently operating with node using [email protected] and [email protected]. Within my jade page, there exists a property like this: input(type='text',class='form-control', placeholder="Username", name='username', ...

Exploring a deep Nested JSON Structure and appending a new attribute

Dealing with a JSON input that can have an undefined number of levels, I am looking to add a specific attribute at all levels. [{ title:' ' , id : ' ', description: ' ', date :' ', children:[{ childre ...

Transforming data from a singular object into an array containing multiple objects with key-value pairs

Looking for assistance with converting data from a single object in JSON format to another format. Here is the initial data: var originalData = { "1": "alpha", "2": "beta", "3": "ceta" } The desired format is as follows: var convertedData = ...

What is the best approach to create a JavaScript search filter function spanning two pages?

Page1.html has a form with a drop-down menu containing options Color and Shape. There is also a submit button. Assuming Page2.html displays various shapes like Blue Square, Red Square, Blue Circle, Red Circle, is it feasible to create a JavaScript file th ...

What is the best way to eliminate the default background color applied to the body automatically?

I'm currently developing a Covid-19 tracking web application and I am using chartJS to showcase data from an API. In my CSS, I have assigned a background color to all elements with an asterisk (*), but for some reason there are empty spaces around the ...

Eliminate duplicate entries from various JSON Arrays

I am facing an issue with a JSON structure containing multiple arrays. My goal is to identify and eliminate any duplicate values across different arrays while keeping the other fields intact. Here is a sample of the structure I am working with: { "Coll ...