Encountering issues when attempting to store input values in an array within local storage

Currently, I am working on a project where I need to store a value from an input field in an array that is stored in local storage. While I have made progress based on previous questions here, I seem to be facing some issues. After entering some data, I used console.log to check if my array is being populated but it shows nested arrays in the console which I am finding difficult to manage.

This is my JavaScript code:

names = [];
names.push(JSON.parse(localStorage.getItem('locname')));
localStorage.setItem('locname', JSON.stringify(names));

function saveData(data) {

  names = [];
  var data = document.getElementById("locationName").value;
  names = JSON.parse(localStorage.getItem('locname'));
  names.push(data);
  alert(names);
  localStorage.setItem('locname', JSON.stringify(names));
}

console.log(names);

In my HTML file, I have an input field with id=locationName and a button with onclick=saveData().

Can anyone point me towards what might be going wrong here?

Answer №1

To utilize local storage in your web application, you can consider implementing the following code snippet:

// Retrieve stored value or initialize empty array.
// Previously, you were increasing the depth of the data structure
// every time by adding another array to "names".
var names = JSON.parse(localStorage.getItem('locname') || "[]");

function saveData(data) {
  var data = document.getElementById("locationName").value;
  names.push(data);
  localStorage.setItem('locname', JSON.stringify(names));
}

Discover a live demonstration on JSFiddle (use developer tools to examine local storage content).

Answer №2

The issue arises when you store the retrieved array in your existing names array from local storage.

Here's a modification:

var names = []; // It is recommended to declare variables before using them
if (localStorage.getItem('locname')) {
    names = JSON.parse(localStorage.getItem('locname'));
}

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

Having trouble assigning a value to a dropdown selection with JQuery

Currently, I am utilizing an @Html.DropDownListFor in my code. Although I can successfully populate the drop-down menu, I am facing difficulties when attempting to set the selected value using JQuery. Below is a simplified version of my code: @{ var listI ...

What is the best way to propagate a react component's props to options following an apollo-client mutation?

How can you effectively pass a react component's props to options after performing a mutation using apollo-client? I am currently utilizing react in conjunction with apollo-client. Within a specific component, I am executing a delete mutation and the ...

Is it possible to determine whether a path leads to a directory or a file?

Is it possible to distinguish between a file and a directory in a given path? I need to log the directory and file separately, and then convert them into a JSON object. const testFolder = './data/'; fs.readdir(testFolder, (err, files) => { ...

What could be the reason for Firefox abruptly terminating inactive XMLHttpRequest connections?

When working with a JavaScript class, an XMLHttpRequest is used to connect to the server. The server sends data slowly, and this process functions well in Chromium. However, Firefox tends to close the connection randomly after a certain amount of time (typ ...

Steps for adding a delete function to an array object

I have confidence in my add method: public void add(Object object) { if (!contains(object) && size !=maxObjects) { set[size] = object; size++; } else System.out.println("Already exists."); } Proof of its correctness c ...

Filter a Vue table by column name with specific conditions

I am working on code that filters a table based on user input. The process involves selecting a column from a drop-down menu, choosing an operator from another drop-down menu, and entering a search value. I want to filter the table based on these criteria. ...

Leverage the power of jQuery to fetch data from a PHP script connected to a MySQL database

It might be a bit confusing, so let me clarify. I'm working on a form where users input a ticket and it gets assigned to a technician based on the service they offer. I have 3 text fields: username, email, and description of the problem. The next fie ...

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...

Converting XML to JSON using Java POJO with the help of Jackson library

I have been working on converting XML to JSON and faced a challenge. Initially, I created a Java class based on the provided XML structure: <CompositeResponse> <CompositeIndividualResponse> <PersonIdentification>2222</PersonI ...

The functionality of the State Params is not functioning as expected

Switch to a different page using parameters by $scope.singlepage = function($url) { $url; console.log($url); $state.go('app.paymentinfo', { "userId": $url}); }; Include state and State param her ...

Having trouble with the performance of a kendo UI treeview connected to a JSON

I have successfully implemented a kendo UI tree using an external JSON file. Everything works fine when I have around 200 nodes, but it takes too long when dealing with a large amount of data. You can view the implementation here. Below is the jQuery co ...

Evaluating QUnit Test Cases

How do you write a test method in QUnit for validating functions developed for a form? For example, let's consider a form where the name field should not be left blank. If the validation function looks like this: function validNameCheck(form) { if ...

Using MySQL with Node.js for JSON parsing techniques

I am facing an issue while trying to use MySQL along with Node.js to communicate with the current Android server. The problem arises when attempting to parse JSON data for sending it to the server. app.get('/main', function(req, res) { if (re ...

Trouble in testing: ComponentDidMount is mysteriously bypassed by Jest/Enzyme when it's supposed to be triggered

In my code, there is a method called componentDidMount that triggers the fetchUser() function. I am currently working on testing the componentDidMount method. Here is the Component Code: static propTypes = { match: PropTypes.shape({ isExact: Pr ...

Experiencing difficulty with writing Array values to memory

I'm currently working with an Arduino along with an Adafruit FRAM memory breakout board. My goal is to retrieve values from an array and then store them in the FRAM. However, I am facing an issue where the saved values are not correct. What kind of co ...

Find the value of the nearest input field using jQuery

I'm working with HTML code that looks like this: <tr> <td class='qty'><input class='narrow' value='1' /><i class='fa fa-trash' aria-hidden='true'></i></td> < ...

HTML FORMS - Transmitting data to multiple forms simultaneously within a single webpage

I'm encountering an issue with passing values to two different forms on the same page. The page contains 16 radio buttons (displayed as boxes) each holding a specific value (e.g., 001). Both forms are meant to capture the selected radio button value a ...

jQuery .click() only triggering upon page load

I've been searching all over the place and I just can't seem to find a solution to my specific situation. But here's what I'm dealing with: Instead of using inline HTML onclick, I'm trying to use jQuery click() like this $(docume ...

How to extract data from URLs in Angular

Looking into how to extract a specific value from the URL within Angular for parsing purposes. For example: http://localhost:1337/doc-home/#/tips/5?paginatePage=1 The goal is to retrieve the value "5". HTML snippet: <a href="#/tips/comments/{{ tip ...

Tips for referencing a string in JavaScript

I am trying to use the showmodal method, but I keep getting an error when passing a string. It works fine with integers, but how can I pass a string in JavaScript? <script> var table = ' <table id="example" class="table table-striped " w ...