Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display a message like "Set your birthday first" if the local storage happens to be empty.

Below is the section where the data should be displayed:

Appreciate all the help!

  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

   <script type="text/javascript" src="http://code.jquery.com/jquery-1.3.2.js"></script>
</head>

<body>



<script>
$(function storeDates(form){
    var operation = "A"; //"A"=Adding; "E"=Editing

    var selected_index = -1; //Index of the selected list item

    var tbClients = localStorage.getItem("tbClients");//Retrieve the stored data

    tbClients = JSON.parse(tbClients); //Converts string to object

    if(tbClients == null) //If there is no data, initialize an empty array
        tbClients = [];

    function Add(){



        var client = JSON.stringify({
            birthday : $("#birth_day").val(),
            patientno:$("#patient_no").val()

        });


        tbClients.push(client);
        localStorage.setItem("tbClients", JSON.stringify(tbClients));

        return true;
    }

    function Edit(){
        tbClients[selected_index] = JSON.stringify({
                    ID    : $("#name").val(),

            });//Alter the selected item on the table
        localStorage.setItem("tbClients", JSON.stringify(tbClients));
        alert("The data was edited.")
        operation = "A"; //Return to default value
        return true;
    }

    function Delete(){
        tbClients.splice(selected_index, 1);
        localStorage.setItem("tbClients", JSON.stringify(tbClients));
        alert("Client deleted.");
    }

    function List(){        
        $("#tblList").html("");
        $("#tblList").html(
            "<thead>"+
            "   <tr>"+

            "   <th></th> "+



            "   </tr>"+
            "</thead>"+
            "<tbody>"+
            "</tbody>"
            );
        for(var i in tbClients){
            var cli = JSON.parse(tbClients[i]);}

            $("#tblList tbody").append("<tr>"+



                                         "  <td ><span class='dayText'><b class='dayclass'>"+         
                                          "Birth  day"+cli.birthday + "</td>" + 

                                         "</tr>");


                $("#patient_number").append(cli.patientno );


    }

    $("#frmCadastre").bind("submit",function(){     
        if(operation == "A")
            return Add();
        else
            return Edit();
    });

    List();

    $(".btnEdit").bind("click", function(){

        operation = "E";
        selected_index = parseInt($(this).attr("alt").replace("Edit", ""));

        var cli = JSON.parse(tbClients[selected_index]);
        $("#deliveryday").val(cli.ID);

    });

    $(".btnDelete").bind("click", function(){
        selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
        Delete();
        List();
    });
});
</script>


<FORM name="f1" id="frmCadastre" > 




       <section id="aligned">


    <input type="text" id="birth_day" name="birth_day" placeholder=" Birth day :" autocomplete="off" tabindex="2" class="txtinput" required><br/><br/>
    <input type="text" id="patient_no" name="patient_no" placeholder=" patient no" autocomplete="off" tabindex="2" class="txtinput" required><br/><br/>



    <input type="submit" name="submit" id="btnSave" class="submitbtn" tabindex="7" onClick="storeDates(this.form); "  />
</form>


   <div id="tblList"></div>
    <div id="patient_number"></div>

</body>
</html>

Answer №1

Firstly, let's explore how to utilize localStorage

if(!localStorage.tbClients) alert("Empty");

Option for accessing data from localStorage

if(!localStorage.getItem("tbClients")) alert("Empty");

Distinguishing between the two methods:

  1. If the key-value pair does not exist, you will receive an UNDEFINED value
  2. If the key-value pair does not exist, you will receive a NULL value

Now to address your query

//retrieving value
var message = localStorage.getItem("SOME_KEY") || "Firstly save your value to localStorage";
console.log(message); 
// if the user has already stored something in localStorage, it will be displayed. Otherwise, show "Firstly save your value to localStorage"

Answer №2

Modify a section of your script with the following snippet:

if (cli.birthday !== "" ) {
  $("#tblList tbody").append("<tr>" +
                "   <td ><span class='dayText'><b class='dayclass'>" +
                "Birth  day : Set Birthday First</td>" +

                "</tr>");
}
else {
  $("#tblList tbody").append("<tr>" +
                "   <td ><span class='dayText'><b class='dayclass'>" +
                "Birth  day" + cli.birthday + "</td>" +

                "</tr>");
 } 

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

What is the best way to receive the information that was transmitted to me through a callback function?

While web development is not my strong suit, I have a question that might sound silly, so bear with me as I explain. Once the user selects their desired purchase, an API call is made to generate a trans_id and redirects them to the bank's payment pag ...

Display or conceal the location where the click event occurs within a single div

progress $(".button-toggle").click(function(e){ $(this).parents.find('#second').toggle(); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="first"> <a href="#" class= ...

Could someone assist me in understanding why VScode is displaying an error stating it cannot locate a module?

node:internal/modules/cjs/loader:1051 throw err; ^ Error: The module '/Users/ben/Desktop/GA/unit2/week5/GA_Project_2/QuotaQuest/index.js' cannot be found. at Module._resolveFilename (node:internal/modules/cjs/loader:1048:15) at Modul ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Ajax fails to transmit data to PHP script

Having encountered an issue with my script that prevents sending data from AJAX to a PHP file, I decided to debug it by logging the form data before running it through the AJAX function. The data obtained was as follows: Form: name=jim&email=info%40te ...

Exploring the new features of utilizing buttons with the onClick method in the updated nextJS version 14.1.3

"implement customer" import React, { useState } from "react"; import { FaChevronLeft, FaChevronRight } from "react-icons/fa"; export default function HeroSlider() { const images = [ "/images/homepage/home-1.jpeg&qu ...

What are the drawbacks of automating the process of generating charts to track time spent on webpages?

!RESOLVED! I am looking to automatically generate charts based on users and their time spent on different pages of a website. I have a file named "log.xml" where I store user information (customers), visited pages, dates, and the time they spent; once I ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Show side by side using javascript

My dilemma lies in having a set of cards that are meant to be displayed inline, but I have to initially hide them using "display: none". When a specific button is clicked, I aim to reveal these cards; however, upon doing so, each card seems to occupy its o ...

Using javascript to transform the entire list item into a clickable link

Currently, I am using PHP in WordPress CMS to populate slides on a slider. Each slide contains a link at the bottom, and my goal is to target each slide (li) so that when clicked anywhere inside it, the user is directed to the URL specified within that par ...

Get documents from Google Drive onto Xamarin Android Player

While developing a Cocossharp application in Xamarin, I ran tests on the Xamarin Android Player. Although it was functional, I encountered an issue with uploading json files from the Emulator File System to my application. I searched for a solution to tr ...

Error: $controller does not function as a controller within another controller

I recently started learning Angular JS and attempted to call one controller within another, but encountered the following error: ionic.bundle.js:21157 TypeError: $controller is not a function at new <anonymous> (http://localhost:8080/itravel/www/js/ ...

Setting up a connection between an Express server and a Mongoose database in

As someone who is relatively new to the express framework and mongoose database, I have mainly worked with relational databases in the past. I am attempting to create a database using the script below. Currently, mongod.exe is running and listening on loca ...

Is it possible to create a development build using Npm with React and Typescript?

I have successfully set up a TypeScript React app by using the command below: npx create-react-app my-app --template typescript However, running "npm start" generates development javascript files and launches a development server which is not id ...

RTM is lacking dropdown navigation menus

In Visual Studio 2013 beta versions, there were dropdown menus at the top of the javascript editor that functioned similarly to those in c# and vb editing. Have these been removed from the RTM or final release, or are they available with a specific version ...

Why does the return value of a function in Node.js and JavaScript sometimes appear as undefined?

I am completely stumped by this issue. I've been trying to figure it out, but so far, no luck.. this is the code snippet function part1(sql, controltime, headers_view, results_view, tmp){ var timerName = "QueryTime"; var request = ne ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

Ensure selected language is maintained when refreshing or changing view by utilizing switch i18n functionality

Hello there, I am facing a challenge with "JavaScript Localization" on my website. The issue is that I cannot figure out how to prevent the DOM from prioritizing the local language of the browser and instead use the language set in the switch as a referenc ...

The Jquery Index() method often results in a return value of -

I have developed a function in JavaScript that creates HTML content. Within the test(test1) function, I am checking if test1.Test__c is null and changing the color accordingly. The line ".table-striped > tbody > tr.testcss" is responsible for changin ...

Issue with React Routes only occurring in the production website

I'm encountering an issue on my personal website that only occurs in production, but not in my local environment. Here's the situation: I have set up the routes as follows const Routes = () => ( <Router> <Route exact path=&quo ...