Collecting information from JSON files

Within the cells of my calendar are placeholders for events, dates, participants, and descriptions. Now, I am looking to populate these placeholders with data previously stored using localStorage.

Unfortunately, my current code is not achieving this. How can I make it work?

To accomplish this task, I have created a JSON object that serves as an array. Each element in the array corresponds to a specific day on the calendar. I am targeting the cell (thisCell) that I click on in order to retrieve the relevant stored information.

    var organizer = [
        //February 9, 2015
        {thisCell.getElementsByClassName("spanEvent")[0].value: JSON.parse(localStorage.getItem("event")),
         thisCell.getElementsByClassName("spanDate")[0].value: JSON.parse(localStorage.getItem("date")),
         thisCell.getElementsByClassName("spanParticipants")[0].value: JSON.parse(localStorage.getItem("participants")),
         thisCell.getElementsByClassName("spanDescription")[0].value: JSON.parse(localStorage.getItem("description"))
        },

        //July 22, 2016
        {thisCell.getElementsByClassName("spanEvent")[0].value: JSON.parse(localStorage.getItem("event")),
         thisCell.getElementsByClassName("spanDate")[0].value: JSON.parse(localStorage.getItem("date")),
         thisCell.getElementsByClassName("spanParticipants")[0].value: JSON.parse(localStorage.getItem("participants")),
         thisCell.getElementsByClassName("spanDescription")[0].value: JSON.parse(localStorage.getItem("description"))
        }
      ]; 

Answer №1

It seems there may be a confusion in your understanding of how to access and modify the content of DOM elements.

The code you have written will not achieve the desired outcome because you are only creating an object, without actually accessing any properties of a DOM element. Additionally, <span> elements do not use the value property to access their content. Instead, they utilize the innerHTML property like most other HTMLElements.

Moreover, the JSON.parse(string) method is used to convert a string into a JavaScript Object{}, which might not be necessary in this case since you are attempting to assign the value to a <span>, which should be a string.

To demonstrate what I believe you are aiming for, I have prepared a fiddle.

HTML

<div class="cell"> 
 <span class="spanEvent"></span>
 <span class="spanDate"></span>
 <span class="spanParticipants"></span>
 <span class="spanDescription"></span>
</div>

JavaScript

localStorage.setItem("event", "someEv");
localStorage.setItem("date", "someDate");
localStorage.setItem("participants", "someParticipants");
localStorage.setItem("desc", "someDesc");

cell = document.querySelector(".cell");
spanEv = cell.querySelector(".spanEvent");
spanDate = cell.querySelector(".spanDate");
spanPart = cell.querySelector(".spanParticipants");
spanDesc = cell.querySelector(".spanDescription");

spanEv.innerHTML = localStorage.getItem("event");
spanDate.innerHTML = localStorage.getItem("date");
spanPart.innerHTML = localStorage.getItem("participants");
spanDesc.innerHTML = localStorage.getItem("desc");

Note: I have used the querySelector() method to select the cell and its elements, but feel free to use any preferred DOM selection technique (getElementsByClassName() is typically faster).

I hope this clarifies things for you!

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

What is the most effective method for merging two arrays in JavaScript?

Can a function be created to generate an array like the following? ["0-AA", "0-BB", "1-AA", "1-BB", "2-AA", "2-BB", "3-AA", "3-BB"] This particular function combines two array ...

In the WordPress REST-API, only the "get" method is permitted

I recently installed the REST-API plugin on my WordPress site and have successfully been able to retrieve posts using the following endpoint: mywp.org/wp-json/wp/v2/posts However, I have encountered a restriction where only "get" requests are allowed. If ...

What is the best way to trigger a function when a button is enabled in Angular 8?

Here is a portion of my sign-in.component.html file. I have created a function in the corresponding sign-in.component.ts file that I want to trigger when the button below becomes enabled. Here is an example of what I am trying to achieve: <div class= ...

The importance of maintaining property order during deserialization with JSON.Net

I am currently working on deserializing a string into a JSON object using JsonConvert.DeserializeObject as shown below: var str = "{ Value: \"File\",Text: \"OWENS &amp; MINOR INFANT - 2228548\"}"; resultArray = JsonConvert.Deseria ...

Most effective method to retrieve yesterday's data

Currently, I'm working on a requirement and I need to validate the logic that I've implemented. Can someone help me with this? The task at hand is to calculate the 1 month, 3 month, and 6 month return percentages of a stock price from the curren ...

Tips for sending a JavaScript object from PHP to AJAX

I've been racking my brain for hours, scouring through countless articles, but I'm still unable to crack this puzzle. Here's the situation: I'm currently tinkering with Chrome extensions and I need to make a server call that will fetch ...

Troubles with the compatibility of javascript and jquery's multiselect plugin

I've been utilizing the multiselect API to create a dropdown with multiple select options. This is my HTML code: <select id="options" multiple="multiple"></select> And this is my JS code: render:function(){ // $('#viewTemp& ...

Having Trouble Showing Loading Component on Next.js v13

Having some issues with setting up a loading component in my Next.js v13 project. I followed the documentation by creating a file called loading.tsx in the src directory, but it's not appearing on the page as expected. I've also included a functi ...

ReactJS Chatkit has not been initialized

I made some progress on a tutorial for creating an Instant Messenger application using React and Chatkit. The tutorial can be found in the link below: https://www.youtube.com/watch?v=6vcIW0CO07k However, I hit a roadblock around the 19-minute mark. In t ...

`The height attribute of the textarea element is not being accurately adjusted`

When I tried to match the width(178px) and height(178px) of my table to the width and height of a text area upon clicking a button, I encountered an issue. While setting the width works perfectly fine, the height is being set to only 17px. It seems like ...

Is it possible to use a '.JS' file downloaded through Node Package Manager (npm) directly in a web browser?

Generally, I am looking to utilize a specific library without relying on Node CMD. For instance: I aim to create a TypeScript playground without having to execute 'tsc.cmd' from "npm\node_modules", instead, I want to directly call the tsc c ...

What is the best way to display an error message when a necessary field is left empty?

I am currently utilizing a plugin to validate my form. My goal is to display an error message on the button when clicked, as all fields in my form are required and need validation. Despite attempting the code below, it hasn't been successful: <Fo ...

"Transferring an array of data to a Laravel controller via AJAX: A step-by-step guide

Is there a way to send arrays of data to the back-end all at once? The Problem 1. This is what I'm currently sending: array:5 [ "_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj" "product_id" => "21" "specification_id" => "6" " ...

Changing the function to operate asynchronously

How can I convert the following code into an asynchronous function? It is currently returning referralUrl as undefined: controller async createReferralUrls() { this.referralUrl = await this.referralService.generateReferralUrl(this.userData.referral ...

A comprehensive guide to effectively formatting Recharts in React: addressing alignment and size management!

While attempting to style two graphs as floating cards, I am encountering difficulties in controlling the sizing and centering of the graphs. Specifically, I am having trouble with the pie chart in this example. To address this issue, I am passing paramete ...

Analyzing and tallying JSON attributes using JavaScript

I have a JSON object with items that I need to analyze in JavaScript. When I view the JSON in the console, there is an element called items that contains an array of relevant information. console.log(json) {current_page: 1, per_page: 100, total_entries: ...

Learn how to organize a div element containing select options using categories such as gender and shoe size, similar to the filtering

Is there a way to sort div elements using a select menu, similar to how it is done on shopping websites? I am struggling with modifying my JS code in order to implement multiple selects. Although I believe my JS code is correct, it doesn't seem to be ...

Transformation of looks post a refresh

Initially, the CSS and appearance of the page look fine when I first open it (after clearing the cache). However, upon refreshing the page, a part of it changes (specifically, the padding direction of a div). This change occurs consistently with each refre ...

Transforming a class instance into a JSON format

I'm encountering an issue trying to convert a class instance into a JSON string. Let's consider the structure of the class: class testclass: value1 = "a" value2 = "b" The json.dumps method is being used like this: t = testclass() json. ...

Guide on how to restrict specific days and dates in MUI React datepicker using a JSON array

I am working on a Laravel application that generates a JSON response containing dates and days of the week that need to be disabled in the datepicker. For instance, here is an example of my datesOff constant when I log it: ['2022-05-08', '2 ...