Do not delete blank notes upon saving

Issue: When multiple notes are created simultaneously, and the same text is entered in the first note and saved, the blank remaining notes are not removed upon page reload or refresh. How can I ensure that empty notes are deleted and only notes with content are saved in local storage? Feel free to test this code on your local machine.

const icon = document.getElementById('icon-plus');
const add = document.querySelector('#plus');

// const show = () => {
//     icon.style.display = "inline";
//}

// const hide = () => {
//     icon.style.display = "none";
//}

const hideBtn = () => {
    add.style.display = "none";
}

const showBtn = () => {
    add.style.display = "flex";
}

const updateLocalStorage = () => {
    const textAreaData = document.querySelectorAll('textarea');
    const notes = [];
    console.log(textAreaData);
    textAreaData.forEach((note) => {
        return notes.push(note.value);
    })

    localStorage.setItem('notes', JSON.stringify(notes));
    // textArea.disabled = true;
}

const addNewNote = (text = '') => {

    const note = document.createElement('div');
    note.classList.add('notes');

    const htmlData = `
              
            <div class="upper-icon">
            <i class="fas fa-edit"></i>
            <i class="fas fa-save"></i>
            <i class="fas fa-trash"></i>
        </div>
            <div class="text-content">
            <div class="main" TextMode="MultiLine"">
            </div>
                <textarea id = "text-box" placeholder="Write a note..."  onmouseover="hideBtn()" onmouseout="showBtn()"></textarea>
            </div>
    `;

    note.insertAdjacentHTML('afterbegin', htmlData);

    document.body.appendChild(note);

    //References //
    const edit = note.querySelector('.fa-edit');
    const del = note.querySelector('.fa-trash');
    const mainDiv = note.querySelector('.main');
    const textArea = note.querySelector('textarea');
    const save = note.querySelector('.fa-save');


    // Delete the note //

    del.addEventListener('click', () => {
        note.remove();
        updateLocalStorage();
    })


    //toggle using edit button //

    textArea.value = text;
    textArea.innerHTML = text;

    edit.addEventListener('click', () => {

        textArea.disabled = false;



        // textArea.classList.toggle('hidden');
    })

    save.addEventListener('click', () => {
        textArea.disabled = true;
        mainDiv.classList.toggle('hidden');
        updateLocalStorage();
     
         
    

        
    })


    textArea.addEventListener('change', (event) => {
        // const value = event.target.value;
        textArea.innerHTML = event.target.value;;
        // if (textArea.value.length > 0) {
        //     updateLocalStorage();
        // }
        updateLocalStorage();
     
    })

    if (textArea.value.length != 0) {
        textArea.disabled = true;
    }

}

// getting a data from local storage //
const notes = JSON.parse(localStorage.getItem('notes'));
if (notes) {
    notes.forEach((note) => {
        addNewNote(note);
    })
}


add.addEventListener('click', () => {
    addNewNote()
});
*{
    (CSS code here...)
}

body{
    (CSS code here...)
}

header{
    (CSS code here...)
}

header .nav{
    (CSS code here...)
}

header .nav h2{
    (CSS code here...)
}

.button{
    (CSS code here...)
 
}

.button button{
    (CSS code here...)
}

.button .icon i{
    (CSS code here...)
}



.button button h3{
    (CSS code here...)
}

.button button:active{
    (CSS code here...)
}

.button button h3:hover{
    (CSS code here...)
}
.button button:hover{
    (CSS code here...)
}

.notes{
    (CSS code here...)
}

.notes .upper-icon{
    (CSS code here...)
}

.notes .upper-icon i{
    (CSS code here...)
}

.notes .text-content{
    (CSS code here...)
}

/* .notes .main{
    (CSS code here...)
} */

.notes  textarea{
    (CSS code here...)
}

.notes .upper-icon i.fa-edit:hover{
    (CSS code here...)
}

.notes .upper-icon i.fa-trash:hover{
    (CSS code here...)
}

.notes .upper-icon i.fa-save:hover{
    (CSS code here...)
}

.hidden{
    (CSS code here...)
}

@media only screen and (max-width: 950px){

    (CSS code here...)
}



@media only screen and (max-width: 500px){
    (CSS code here...)
}

footer {
    (CSS code here...)
  }
<!DOCTYPE html>
<html lang="en">

<head>
    (HTML code here...)
</head>

<body>

    (HTML code here...)

</body>

</html>

Answer №1

Before saving notes to local storage, it is important to verify if the notes have content or are empty. Only when the notes are not empty should they be stored in local storage.

const updateLocalStorage = () => {
    const textAreaData = document.querySelectorAll('textarea');
    const notes = [];
    console.log(textAreaData);
    textAreaData.forEach((note) => {
        if(note.value){
            return notes.push(note.value);}
        })

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

NodeJS: The module failed to automatically register itself

Exploring the capabilities of IBM Watson's Speech to Text API, I encountered an issue while running my NodeJS application. To handle the input audio data and utilize IBM Watson's SpeechToText package, I integrated the line-in package for streami ...

"Experiencing a callstack overflow due to multiple carousels on one page using Jquery or Vanilla

Currently, I am working on implementing a Jquery infinite autoplay multiple carousel. What I have done is created two separate carousel blocks on the same page within the body section. <div class="rotating_block"> <div class="bl ...

I'm having trouble sending a string to a WCF service using jQuery AJAX. What's preventing me from sending strings of numbers?

Something strange is happening with my web service when using jquery ajax - I can only pass strings containing numbers. This was never an issue before as I would always just pass IDs to my wcf service. But now that I'm trying something more complex, I ...

Icons positioned absolutely outside of components will not be responsive to user interactions

How can I ensure that the icon on my tab bar can be clicked only when it covers a specific part of the screen, and not when it is in other areas? Any suggestions on how to fix this? Image Below is the code for the tab bar: <View style={{ background ...

Tips on effectively utilizing CSS sprites without a border on images

I am currently working on optimizing my website by using sprite images. The image I am using is in png format and looks like this: https://i.sstatic.net/pFhPq.png Here is a snippet of my CSS code: .bg-upperbar_1 { width: 55px; height: 55px; bac ...

Navigating the world of cryptocurrency can be daunting, but with the right tools

Hello fellow developers, I've encountered some difficulties with cryptocurrency in my Nativescript project. I am attempting to incorporate the NPM package ripple-lib into my code, but I have been unsuccessful using nativescript-nodeify. How can I suc ...

Clear Redis sorted set scores following zremrangebyscore operation

Currently, I am utilizing a Redis sorted set to maintain values in a specific order. Here is an example: score | data 0 | a 1 | b 2 | c 3 | d There are situations in my application where I need to delete certain entries. For instance, ...

Bringing a JavaScript file into an Ionic/Angular 2 project

I have been attempting to integrate a simple JS library into Angular 2. The library in question is JIC.js. var jic = { /** * This function takes an Image Object (JPG or PNG) and returns a compressed new Image Object * @param {Ima ...

What is the best way to navigate back to the previous page?

<html> <body> <form action="index.php"> <button type="submit" name="logout" style="background:lawngreen ;" class="btn btn-default">Logout</button> </form>` <?php $btn=$_POST['logout']; if(isset ...

Aligning a child element in the center along the horizontal axis within a parent container that is smaller in width than

I have been attempting to center an <img> element horizontally within a <div> that is narrower than the image itself. The <div> has overflow: hidden applied to it. For example, if the image is 500px wide and the DIV is 250px wide, is the ...

Tips for aligning two divs side by side: Ensure one of the divs is centered within the container that holds both divs

How would you align two divs next to each other, with one of them centered within the container? I'm trying to figure out how to position the second div right beside the first one and have it expand to the right. Any ideas? Check out this example : ...

The process of utilizing RxJS for server polling is a

My goal is to constantly update client-side data by polling the server. To achieve this, I have set up a dispatcher that triggers an action labeled FRONT_PAGE. This action is initiated when the app launches and the client is supposed to send requests every ...

Automatically populate the options of a dropdown menu using jQuery

I am a beginner in the world of Javascript, JSON, and jQuery. I am seeking some guidance as I navigate through this new territory. On my JSP page, there is a drop down list that needs to be populated with content when the page loads. To achieve this, I hav ...

Node.js and Couchbase integration: A closer look at the functionality of the add() method

As I dive into learning about couchbase, I encountered a basic issue with inserting data using the add() method in my couchbase instance. Despite troubleshooting, something seems amiss in my code and I'm unable to pinpoint the exact reason. var http ...

Looking for advice on how to design a custom JavaScript widget?

I am currently working on a web application and I am in the process of developing a feedback form widget that users can easily embed on their websites. The data submitted through this widget will be securely stored within my web application. One important ...

Displaying the error message "No results found" in PHP AJAX live search with multiple values is not possible

I recently went through a tutorial on Most of it worked smoothly after setting it up on my local machine. However, I encountered an issue when searching for data not present in my database. I expected to receive an error message stating "No result found o ...

How can I simulate pressing the ENTER key in Selenium without selecting any element?

Having trouble using the firefox selenium plugin and sending the enter key after pasting text? The ENTER key press should not interact with any other element on the page, just a simple 'dumb' ENTER key press. error [error] Element name=code not ...

Node.js client encounters ENOBUFS error due to excessive number of HTTP requests

Currently, I have the following setup: An end-to-end requests system where a node.js client communicates with a node.js server. However, the issue arises when the client fails with an ENOBUFS error in less than a minute. client: (function(){ var lo ...

Creating this design using only HTML and CSS is possible by following these steps

I attempted to create this design using only HTML and CSS but unfortunately couldn't achieve it. Can anyone provide me with some assistance? Thank you in advance Check out the image on imgur.com ...

Incorporate pictures from Firebase into the table

Hey there! I'm facing an issue where I am trying to add images to a table but they're not showing up. Any ideas on what might be causing this? Here's the jquery code snippet: $(document).ready(function() { var brandsRef = firebase.data ...