Issues with storing data locally

I am currently working on developing a web application where clicking a button saves its ID to local storage and changes its style. However, I am facing an issue where the ID of the last clicked button replaces the ID of the previously clicked button in local storage. Here is a snippet of my code:

$(document).ready(function(){
    $("li a").click(function(){
        $("li a").removeClass('active');
        $(this).addClass('active');
        localStorage.setItem('active', $(this).html())
    });

    var active = localStorage.getItem('active');

    $("li a").each(function(index){
        if($(this).html() == active) {
            $(this).addClass('active');
        }
    });
});

Your help in resolving this issue would be greatly appreciated. Thank you.

Answer №1

localStorage works as a convenient key-value storage system. When you set a key, it will replace the value associated with that key if one already exists. This feature allows for easy manipulation of data stored in localStorage. For instance, you can store an array as a string in localStorage and later retrieve it to make additions or changes.

// Example of storing an array in local storage
localStorage.setItem('myArray', JSON.stringify([1, 2, 3]));

// Retrieve the array, modify it, and then update it in local storage
var myArray = JSON.parse(localStorage.getItem('myArray'));
myArray.push(4);
localStorage.setItem('myArray', JSON.stringify(myArray));

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

"Toggling the parent element through jQuery within a search function

I have a similar structure in my table: <input id="mySearch" placeholder="Search..." type="text"/> <table> <th>Main header</th> <tbody id="searchable"> <tr class="parent"><td>Parent</td></tr> ...

Sending data using Ajax in a Spring application

When using a post Ajax to call a controller, I am encountering an issue where I do not receive a response and instead get an error. Upon further investigation, it appears that the controller is receiving null for the user name, even though the ajax functi ...

What is the reason behind CSS absolute positioning consistently being bound to the document body instead of the containing div?

Need help with HTML/CSS formatting. The webpage size is set to 1000 pixels by 1000 pixels and enclosed within a box. To aid alignment, I've added a temporary solid black border around the elements that will be hidden later on. The layout consists of ...

What is the method for adding color to the select and option fields?

On my website, I have created a contact form and I am trying to customize the select field by adding colors like other fields. However, when I choose an option from the select field, it is not showing up. Can you please help me identify what mistake I migh ...

Connecting Angular directive to a controller

While diving into some Angular JS tutorials, I decided to apply what I learned in the Ionic framework. Unfortunately, I hit a roadblock when attempting to create a reusable HTML control because the model isn't syncing with the view as expected. Here&a ...

Angular Material layout uses columns for large displays and switches to rows for smaller ones

I'm attempting to create a layout where there are 2 columns side-by-side for larger screens, and a single column for smaller screens. My initial attempt using this JSFiddle: https://jsfiddle.net/suunyz3e/1637/ was unsuccessful... Is there a way to e ...

scrollbar located outside of the visible content area

Within a scrollable div, I have two nested divs. The first has a fixed size to hold header data, while the second adjusts to the page containing content corresponding to the headers. The outer div scrolls horizontally along with the headers, while the inn ...

Animating the background color using jQuery

I'm attempting to add animation to a div element upon clicking a button using a function, but it seems to not be functioning correctly. Any ideas on what the issue might be? JavaScript: function caller() { $("#hfont1").animate({ "backgro ...

The Ajax call is being made twice

A code snippet using jQuery to send data is being executed twice with a single click, resulting in two HTTP requests both receiving a 200 response. $(function() { $('input[type=submit]').click(function() { $(this).unbind("click"); ...

Error encountered: $(...).dataTable(...).row does not exist as a function

I am currently working with a datatable and I would like to implement a feature where the selected row is removed when clicked on. Below is the code snippet for the datatable: $('.data-table').dataTable({ "aaSorting": [], "oLanguage": {"sSe ...

Having issues with regEX functionality in an Angular form

I need to validate a phone number using regEX. My criteria is as follows: 10 digits alpha/numeric, where an Alpha CHAR is in the 4th position (excluding hyphens). For example: 586R410056  NNN ANN NNNN  (NNN) ANN NNNN  NNN-ANN-NNNN  (NNN) AN ...

Retrieve the IDs of list elements in order to dynamically update a div using AJAX

I'm facing a bit of a challenge at the moment. I have a webpage that uses jQuery to load three different views: one displaying all categories associated with the user, another showing the image and name of items within the selected category, and a thi ...

Manipulating events through adjusting values of a JQuery-UI range-slider

My range-slider's values are being set with the code: $('...').slider( 'values', [ 0, 10000 ] );. However, I am facing an issue where this line triggers the change( event, ui ) event twice. Is there a way to ensure it only triggers ...

Slide containing Ionic list views

In my Ionic app, I am using ion-slide-box with 3 slides. Each slide contains an ion-list (table view) with varying numbers of items. The issue is that when scrolling through the shorter list items, it shows empty content due to the taller sibling list taki ...

Validating Angular for controls that are not in a form

I am working on validating a form using reactive form group for non-form controls. As part of my form, I am incorporating custom components. Take a look at the example below: <form [formGroup]='formGroupName' > <input type='text&a ...

How can I center an image next to text on two lines, that is compatible with IE7?

I am trying to align an image (logo) with text in two lines - the website title and a brief description. Here is my attempt using HTML: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional ...

Evaluating the distances among various points

Using the Pythagorean Theorem, I aim to calculate the distance between a series of points in an array by iterating through them and identifying the n closest points. However, I'm struggling to determine how to compute the distance (d) between each ite ...

Incorporating visuals into your HTML email

After struggling with this issue for quite some time, I finally managed to get it to partially work. However, the code displays the three images correctly embedded on some email clients, attaches them as attachments on others, and doesn't show them at ...

jQuery is notorious for incorporating front-end JavaScript libraries that are riddled with security flaws

After conducting an optimization analysis of my website using Google Lighthouse, I came across a "Best Practices" issue that raised concerns: Some third-party scripts may pose security vulnerabilities that can be easily exploited by attackers. You can ac ...

Can FancyBox be applied to a button in Ruby?

Can FancyBox be used on a button element? document.getElementById("btn-dispos").addEventListener("click", function(){ $.ajax({ type: "get", url: path_to_load_plages_dispo_fournisseurs, ...