When storing data in the local storage, ensure that duplicates are not being unintention

I'm currently developing a daily task organizer for work. The data is being pulled from local storage successfully. I am facing an issue while iterating through an array of objects and trying to retrieve data based on matching IDs. These objects have two properties - hour and description, with the hour acting as the unique identifier. However, when retrieving the data from localStorage, the targeted object's data is duplicated in every textarea.

Is there a way to display the data only in the corresponding textarea with the matching ID?

The problematic section of my code seems to be:

for (var i = 0; i < timeBlockArr.length; i++) {

  var timeBlockId = $(".time-block").attr("id");
  if(timeBlockArr[i].hour === timeBlockId) {    
    $(".time-block .description").val(timeBlockArr[i].description);
  }
}

You can view the working project on jsFiddle here: https://jsfiddle.net/j9hepL2b/

Answer №1

While looping through your localStorage objects, the value of timeBlockId remains constant regardless of the element currently being processed.

The line $(".time-block") represents an array of elements with the class time-block.

var timeBlockId = $(".time-block").attr("id");

However, using jQuery's .attr() method will only retrieve the ID of the first element in that array as stated in the documentation:

The .attr() method retrieves the attribute value for only the initial element within the matched set.

Thus, the output of console.log(timeBlockId) will always be "hour-9".

If I interpret your intention correctly, the if statement may not be necessary at all. Consider this alternative approach:

for ( var i = 0; i < timeBlockArr.length; i++) {

    const selector = '#' + timeBlockArr[i].hour + ' .description';

    $(selector).val(timeBlockArr[i].description);
  
}

This code selects the element with the class .description (i.e., the textarea) which is a descendant of the element with the ID #hour-9, #hour-10, and so on, and updates the textarea's value using .val().

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

Angular and React: A Comparison of Their Binding Mechanisms

As I embark on my journey with React, I've grasped the concept of binding "this" in React. However, I'm puzzled about how Angular manages "this". React class Product extends React.Component { a= "mdb" constructor(props) { super( ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

Storing multiple files in a single database field using C# byte arrays

Currently faced with the task of streaming multiple files to a database and retrieving them, I am challenged by the fact that the number and names of these files are unknown. Additionally, there is only one field in the database to store all the files. How ...

Failure to populate AngularJS view

I am a beginner in AngularJS and I am attempting to create a page similar to the example provided here. While the example works perfectly when copied from the link above, I am facing difficulties trying to integrate it into my folder structure as displaye ...

Leveraging Attr Jquery

I find myself in a perplexing situation My attempt to insert a button into a div with a specified width has hit a roadblock $('#main').append('<button id="hello" type="button" style="width:100px">Click Me!</button>'); Des ...

Invoking Redux actions within a React component

I'm attempting to send a variable to a Redux action, however, it seems that the action is receiving undefined. What could be causing this issue? index.js - location of action invocation import React from 'react' import { connect } from &ap ...

Fascinating CSS rendering glitch observed on zooming in: all browsers create a noticeable gap between containers except for Firefox

I'm experiencing a rather intriguing and peculiar issue with css styles when zooming in and out on the browser. Specifically, I've created a material ui card where the background-color changes upon clicking with an animation effect. The animati ...

Angular and AngularJS directives work together to indicate events on a line chart

Currently, I am creating a dashboard using AngularJS along with Angularjs-nvd3-directives, mainly focusing on line charts. I am interested in adding markers to the chart for specific events. For instance, if I have a time series data, I want to be able to ...

Encountering weathers.map is not a function error while using React.js with OpenWeatherMap integration

Struggling with React.js for a college project and need some help. The error message I keep encountering is: weathers.map not a function I know it's probably something simple, but for the life of me, I can't figure it out! My project structure f ...

Acquire unique keys from a JSON array without duplication

When a request is sent to an Elasticsearch cluster, the returned JSON array may look like this: [ { "_type": "Event example", "_source": { "democarrier_s": "vodafone UK", "m-Ecosystem_s": "iOS", "dem ...

I am in desperate need of assistance to grasp the concept of writing a class (including the declaration and definition) solely by analyzing a main program and the corresponding sample output

I've been analyzing an example and attempting to decipher the process of writing the .h and .cpp files based on observation of the main file and its output. In this case, there is a class named Flex: #include <iostream> #include "flex.h" using ...

Trying to connect to a socket.io server from a remotely hosted page returns an error stating "require undefined."

Trying to connect to a socket.io server hosted on Heroku from a remote client. The client site is hosted on XAMPP running on my PC. Encountering an issue with the client-side JavaScript const io = require("socket.io-client"); An error is thrown in the co ...

Is it possible to include three sorting states in jQuery DataTables: ASC, DESC, and NO_SORT?

When clicking on a column header in jQuery DataTables, the sorting order toggles between ascending (Down Arrow) and descending (Up Arrow). However, I am looking to customize this behavior: 1st-click ascending 2nd-click descending 3rd-click no-sorting 4th- ...

What are the steps to configure an AngularJS application with onDeviceReady and initialization functions for Cordova integration?

I'm currently developing my first Cordova application using AngularJS, and I find myself a bit unsure about how to properly organize the initial JavaScript for a Cordova project. At this point, I have made some modifications to the default index.js f ...

Is it possible to programmatically include a getter method to a class in JavaScript or TypeScript?

My current focus is on TypeScript and I'm exploring the decorators functionality. I would greatly appreciate some guidance or expert knowledge on JavaScript capabilities in this area. I am curious about dynamically adding a getter method to a Prototy ...

The JQuery chosen dropdown experiences a visual issue when placed inside a scrollbar, appearing to be "cut

Good day, I've been using the jQuery "chosen" plugin for a dropdown menu, but I encountered an issue with it being located in a scrollable area. The problem is that the dropdown items are getting cut off by the outer div element. I have provided a si ...

Automatic Addition of Row Numbers Enabled

I'm currently exploring coding and experimenting with creating a scorekeeper for family games. I've managed to add rows dynamically and automatically sum up the entered information in the "total" row at the bottom. However, I'm facing an iss ...

The use of a nested loop in jQuery to render elements using the appendPe function only displays

Trying to fetch data from a drinks API using an AJAX call and then looping through to display the ingredients on the page. However, only the last item in the loop is being displayed when appending the results with jQuery. I am aware of some null values and ...

Sorting a select element using Javascript/JQuery while taking into consideration the label attribute present in the options

It came to my attention that the jQuery options and examples only covered the text and value attributes, causing errors when attempting to add the label attribute. I am looking for a way to include the label attribute in the sorting process, especially whe ...

Using RequireJS with ASP.NET MVC for Efficient Script Bundling

There are a couple of things I am puzzled about. I have been delving into learning RequireJS and employing it in tandem with ASP.NET MVC bundling & minification. I have set up a separate configuration file for RequireJS which contains the bundling details ...