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

I am looking to grasp the concept of the Conditional ternary statement

I attempted to convert the code below into a ternary operator, but unfortunately ended up with an undefined result. Could someone please clarify where I made a mistake and advise on how to correct it properly? Thanks in advance. const plantNeedsWater = f ...

Save documents in Firebase storage

Currently in the process of developing a web application using Firebase and Angularjs as my frontend tools. Curious to know whether it's feasible to store various file types within the Firebase DB. Could you shed some light on any potential limitatio ...

What is the best method for deleting the div with id "__next" in Next.js?

I'm currently working on a website using Next.js and I'm aiming to create a header with a position: sticky; effect. Nevertheless, Next.js automatically inserts a div with the attribute id="__next" at the top of my website without my co ...

What is the best way to populate a text field in AngularJS with multiple selected values?

Seeking assistance with a dynamic text field value that changes based on an AngularJS post request. I am looking to modify this value through multiple selected options. Here is the HTML code: <tr ng-repeat="opt in myData"> <td> & ...

What is the best way to parse a JSON file in Angular?

Can you please explain how to read a JSON file? I have been able to successfully read a JSON file using a controller, but when I try to read it from a factory, the content is null. Why is this happening? http://plnkr.co/edit/THdlp00GuSk1NS6rqe5k?p=preview ...

Combining numerous objects into one object within an array, each with distinct keys, and displaying them using FlatList

I'm struggling to present this information in a FlatList. Array [ Object { "-N1gqvHXUi2LLGdtIumv": Object { "Message": "Aeaaeaea", "Message_CreatedAt": 1652167522975, "Message_by_Ema ...

Arranging Angular Cards alphabetically by First Name and Last Name

I am working with a set of 6 cards that contain basic user information such as first name, last name, and email. On the Users Details Page, I need to implement a dropdown menu with two sorting options: one for sorting by first name and another for sorting ...

Exploring SubjectBehavior within my UserService and Profile Component

Within my ShareService, I have the following code snippet: isLogin$:BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); <==== default value is false CheckUser = this.isLogin$.asObservable(); public isLogin (bool){ ...

Using DART language to read a JSON file stored locally on the client side, eliminating the need for a server

Having some trouble reading data from a JSON file with the following code: void fetchData(Event e){ var path='json/data.json'; var request= new HttpRequest(); request ..open('GET', path) ..onLoadEnd.liste ...

Issue with AsyncTaskLoader not loading JSON data into RecyclerView after returning from a different fragment

After sending a POST request from the AddItem fragment to add a new JSON item, you are redirected back to the ItemListFragment. However, the newly added item does not immediately show up on the RecyclerView. You have to manually refresh the RecyclerView us ...

What is the most effective method for grouping state updates from asynchronous calls in React for efficiency?

After reading this informative post, I learned that React does not automatically batch state updates when dealing with non-react events like setTimeout and Promise calls. Unlike react-based events such as onClick events, which are batched by react to reduc ...

"""Exploring the use of query strings with jQuery for Ajax pagination

Here's the issue I'm facing (apologies for any mistakes in my English): I've been using a library called "Jquery_pagination" and the pagination functions perfectly without any issues. However, there is one problem. When a user clicks on a s ...

Retrieving keys from a JSON object

As I develop the scoring web application using Python's Flask framework, I have a JSON file with specific data regarding user scores on different pages: { "page1": { "pr": { "user": "A", "timestamp": "2017-02-23T23 ...

Updating local variable value in Node.js from an event listener

How can I modify a local variable within an event handler, listener, or function? export async function mis() { let result; // <--------- LOCAL VARIABLE I WANT TO MODIFY (currently undefined) const m = await spawn(`/cmd`); m.stdout.on('data ...

JavaScript Error: Unable to determine the value of a null property

Is there a way to validate the user's input in real-time on an HTML form? Take a look at the following HTML code: <div class="col-md-2"> <input class="form-control" name="nbequipement" id="nbequipement" placeholder="" type="text"> ...

Combining Summernote images with Node.js using Express.js

While there are numerous solutions available for handling the Summernote file-upload in PHP, I have struggled to find a satisfactory solution for Node.js. Here is My JavaScript: $(document).ready(function() { // $('#summernote').summernote( ...

extracting data from JSON and storing it in an array

JSON: var res = { "response": { "data": { "profilesearchsnippet": [ [ { "profileInfo": { "firstname": "Sundar", ...

What is the solution to resolving the problem indicated by the error message "at process.processTicksAndRejections (node:internal/process/task_queues:95:5)"?

I encountered an issue while attempting to send a token to the user for password reset. The error message I received is as follows: Error: there was an error sending the email, try again later at exports.forgotPassword (C:\\Users\\Abdur ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...

Simply touch this element on Android to activate

Currently utilizing the following code: <a href="http://www...." onmouseover="this.click()">Link</a> It is evident that this code does not work with the Android Browser. What javascript code will function properly with the Android Browser as ...