Tips for applying a class to an element depending on data stored in Local Storage using JQuery

I am currently working on a TODO list project with functions to save and delete records already in place. However, I am facing challenges with the functions for marking items as important and done.

One method I use is to retrieve saved items from Local Storage as an array:

function get_todos() {
    var todos = new Array;
    var todos_str = localStorage.getItem('todo');
    if (todos_str !== null) {
        todos = JSON.parse(todos_str);
    }
    return todos;
}

Another method I use is to save records in Local Storage:

function add() {
    var task = "00" + document.getElementById('task').value;
    var todos = get_todos();
    todos.push(task);
    localStorage.setItem('todo', JSON.stringify(todos));

    show();

    return false;
}

To differentiate between items marked as important or not important, I label them with two digits at the beginning: 00 for undone and/or unimportant, and 01 for done and/or important respectively. When changing these numbers in Local Storage, I follow this approach:-

//If the second digit is 0, then the task is not important
function markAsImportant(){
    var id = parseInt(this.getAttribute('id'));
    var todos = get_todos();
    var task = todos[id].replaceAt(1, "1");
    console.log(task);
    todos.splice(id, 0, task);
    todos.splice(id+1, 1);
    localStorage.setItem('todo', JSON.stringify(todos));
    show();

    return false;
} 

This method works effectively as intended.

Now, my goal is to visually represent the importance of each item by adding a specific class to those marked as important (with the second character being '1') in the TODO list representation:

function show() {
    var todos = get_todos();

    var html = '<div class="list">';
    for(var i=0; i < todos.length; i++) {
        if (todos[i].charAt(1) == '1') {
            console.log("important");
            $('.item').addClass('important');
        }
        else{
            console.log("not important");
        }

        html += '<div class="item"> <input type="checkbox" class="check" id="' + i  + '"> ' +' <div class="title">' +  todos[i].substring(2) +  '</div> <div class="tools"> <span class="tag" id="' + i  + '"> <img class="important-img" src="resources/important.png"> </span> <span class="delete remove "  id="' + i  + '"> <img src="resources/thrash.png"> </span> </div></div>';
    };
    html += '</div>';


    document.getElementById('todos').innerHTML = html;

    var deleteButtons = document.getElementsByClassName('remove');
    for (var i=0; i < deleteButtons.length; i++) {
        deleteButtons[i].addEventListener('click', remove);
    };

    var doneButtons = document.getElementsByClassName('check');
    for (var i=0; i < doneButtons.length; i++) {
        doneButtons[i].addEventListener('click', markAsDone);
    };

    var importantButtons = document.getElementsByClassName('tag');
    for (var i=0; i < importantButtons.length; i++) {
        importantButtons[i].addEventListener('click', markAsImportant);
    };

    var listItems = document.getElementsByClassName('item');
    for (var i=0; i < listItems.length; i++) {
        console.log(listItems[i]);
        $(listItems[i]).attr('id', i);
    };
}

However, I am facing issues with adding the 'important' class to the desired items. How can I successfully achieve this modification?

Answer №1

Make sure to include the HTML in the DOM, otherwise $(".item") won't be recognized. Try using this adjusted code snippet:

for (var i = 0; i < todos.length; i++) {
  html += '<div class="item';
  if (todos[i].charAt(1) == '1') {
    console.log("important");
    html += ' important'; // Remember, keep the space before "important"
  } else {
    console.log("not important");
  }
  html += '"><input type="checkbox" class="check" id="' + i + '"> ' + ' <div class="title">' + todos[i].substring(2) + '</div> <div class="tools"> <span class="tag" id="' + i + '"> <img class="important-img" src="resources/important.png"> </span> <span class="delete remove "  id="' + i + '"> <img src="resources/thrash.png"> </span> </div></div>';
}

Replace your existing for loop with this code and share your results in the comments below!

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

The datepicker in Vuetify is failing to display any dates

My date picker modal expands correctly, but the dates are not showing up. https://i.stack.imgur.com/azC1w.png The datepicker functions perfectly on the Codepen demo, displaying the dates as expected. However, when I try to implement the same code in my ap ...

The methodology of executing a Javascript function

I have the following code snippet: (function() { $(document).ready(function() { //Event handlers $('.project-delete').on('click', function() { deleteProject($(this)); }); $('.keyword-delete').on(&ap ...

ASP.Net MVC page is sending data to the controller without displaying the record ID in the address bar

In my web application, I have implemented a Razor page to display a list of meetings. Each meeting has a unique ID which is associated with a link. Clicking on this link loads another Razor view that shows the details of the selected meeting. Within this v ...

Having trouble maintaining the original events on a cloned element

My goal is to duplicate an element passed into a function and retain all associated events, including ones like $('.example').on('click', function(e) ... )} that are defined within the document ready. Here's what I'm trying: ...

Achieving perfect alignment for CSS heading and floated controls in the center of the page

I seem to encounter situations where I need inline-block elements on opposite ends of the same "line" while also needing them to be vertically aligned. Take a look at this example: http://jsfiddle.net/96DJv/4/ (focus on aligning the buttons with the headi ...

The AJAX request seems to be malfunctioning despite the fact that both the PHP and JS files function correctly independently

I have set up an AJAX call and tested the JS file by alerting out the POST values being sent along with the data string. Everything seems fine at that point. I then passed these values to the PHP file where they are required, making sure to keep it simple ...

Design a clickable div element embedded within an interactive article using HTML5

Currently, I am facing an issue with placing clickable div elements inside an article tag in HTML5. The problem is that when I try to click the divs, it registers as a click on the article itself. Below is an example of my code: HTML: <article id=&apo ...

Whenever I attempt to start my ReactJS project using the command line with `npm run it`, I keep encountering an error

Encountered an issue with the webpack-dev-server script while working on my project. Ensure that your node.js and npm versions are up to date. If they are, the problem might lie within the reactjs package rather than npm itself. Kindly inform the author ab ...

The Jquery calculation feature sometimes mistakenly adds an incorrect value before calculating the correct value

Working on a calculator that accurately computes the field price and displays it, but facing an issue where the correct answer seems to merge with another value (likely from data-price as they match). Snippet of the code: var updateTotal = function() { ...

PHP is returning an empty response during an AJAX request

I am facing an issue with my AJAX request where I am trying to return a simple echo, but for some reason, it's not working this time. Even after stripping down the code to its bare essentials, the response is still blank. Javascript function getUs ...

I possess a primary menu with several submenus, yet I am encountering difficulty accessing the submenus. My goal is to efficiently navigate and access the appropriate submenu within the main menu

I am facing an issue with my CSS where the sub menu is currently showing from the left side, but I would like it to slide up and down instead. .outer { width: 100%; text-align: center; background-color: Gray; padding-top: 20px; bord ...

What is the best way to generate a fresh JSON object within a react hook function?

I am currently facing two issues. Firstly, I am having trouble figuring out how to add/update the JSON items within a hook. Secondly, React seems to be restricting me from using the name that is stored in a previous JSON file. I am open to exploring alter ...

Having trouble understanding why adding raw HTML is yielding different results compared to generating HTML using jQuery

I need assistance with two jsFiddles: http://jsfiddle.net/kRyhw/3/ http://jsfiddle.net/kBMSa/1/ In the first jsFiddle, there is code that adds HTML to my ul element, including an 'X' icon in SVG format. Attempting to recreate this functionali ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

Using a variable as a URL parameter in a jQuery ajax request: tips and tricks

$.ajax({ type:"POST", url:"hostname/projfolder/webservice.php?callback=statusReturn&content="+str_table, contentType: "application/json; charset=utf-8", crossDomain:true, dataType:'jsonp', succe ...

React Weather App: difficulties entering specific latitude and longitude for API requests

I have successfully developed an app that displays the eight-day weather forecast for Los Angeles. My next objective is to modify the longitude and latitude in the API request. To achieve this, I added two input fields where users can enter long/lat values ...

Unable to retain the textbox value upon the initial button click in ReactJS

Can you please assist me? I am trying to save textbox data to hooks, but when I click the save button, the data is not immediately saved to my useState. I have to click the save button again in order to save it to the hooks. Here are the relevant code sni ...

My goal is to ensure that when a user copies the URL of a website from the address bar and pastes it into a social media app, the link automatically transforms into the title of

Similar to the process in Airbnb where a copied URL is pasted in Slack and replaced with specific text along with the site URL I have tried adding og:title, description, and images, but cannot figure out how to handle this issue. Any assistance would be a ...

Using AdBlock Plus will conceal elements on a webpage that have ids or classes containing the term "ad"

In my website, there are two divs: one with the ID of ad_holder and the other with the ID ad_buttons. While testing the site on Mozilla with Adblock Plus installed, I observed that both divs were hidden. Upon further investigation, I discovered that Adblo ...

I am having difficulty in receiving accurate speech recognition through the microphone while using the Azure Speech to Text service in a

I developed a code in React JS to extract text from speech using the microphone, but unfortunately it is not able to recognize or identify the speech. I have tried various options but all efforts seem to be in vain as no errors are being shown. const start ...