Click here to Skip to main content
15,513,489 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
How to read the previously stored array, if there are any.

Is adding the object to the array working in this code?

Store/update the array in localStorage, is this task being run or not properly? I'm getting confused

What I have tried:

<!DOCTYPE html>
<html>
  <head>
    <title>Converting JSON Data to HTML Table</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <style>
      th,
      td,
      p,
      input {
        font: 14px Verdana;
      }
      table,
      th,
      td {
        border: solid 1px #ddd;
        border-collapse: collapse;
        padding: 2px 3px;
        text-align: center;
      }
      th {
        font-weight: bold;
      }
    </style>
  </head> 

  <body onload="CreateTableFromJSON()">
    <div class="col s4">
      <div class="container blue card">
        <h2>Input Form</h2>
      </div>
      <form class="container card">
        <p>
          <label>Name</label>
          <input class="input" type="text" id="first_name" />
        </p>
        <p>
          <label>Date Of Birth</label>
          <input class="input" type="text" id="date_of_birth" />
        </p>
        <p>
          <label>Email</label>
          <input class="input" type="text" id="email" />
        </p>

        <p><button type="button" class="btn blue" id="save">Submit</button></p>
        <input type="reset" value="Reset">
      </form>
      
      <br />
    </div>
    <p id="showData"></p>
  </body>

  <script>
    
    let localData = localStorage.getItem("localData");

    if (!localData) {
      // default data
      const data = {
        cols: ["Serial No.", "Name", "Date Of Birth", "Email", "Action"],
        rows: [
          {
            serial_no: "1",
            name: "Amar",
            date_of_birth: "01/01/1990",
            email: "def@gmail.com",
          },
          {
            serial_no: "2",
            name: "Abhi",
            date_of_birth: "30/10/1996",
            email: "xyz@gmail.com",
          },
          {
            serial_no: "3",
            name: "Alex",
            date_of_birth: "12/12/1999",
            email: "abc@gmail.com",
          },
        ],
      };
      localStorage.setItem("localData", JSON.stringify(data));
    }

    $("#save").on("click", function () {
      var first_name = $("#first_name").val();
      var date_of_birth = $("#date_of_birth").val();
      var email = $("#email").val();
      //   var count = $("#myTable tr").length;
      let data = getData();

      if (first_name != "" && date_of_birth != "" && email != "") {
        let item = {
          serial_no: data.rows.length + 1,
          name: first_name,
          date_of_birth,
          email,
        };
        // append into the array
        data.rows.push(item);

        // update local storage
        UpdateLocalStorage(data);

        CreateTableFromJSON();
      }
    });

    function CreateTableFromJSON() {
      // CREATING DYNAMIC TABLE.
      let table = document.createElement("table");
      let data = getData();

      // HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
      let tr = table.insertRow(-1); // TABLE ROW.

      for (let i = 0; i < data.cols.length; i++) {
        var th = document.createElement("th"); // TABLE HEADER.
        th.innerHTML = data.cols[i];
        tr.appendChild(th);
      }

      var th = document.createElement("th"); // TABLE HEADER.
      tr.appendChild(th);

      // ADDING JSON DATA TO THE TABLE AS ROWS.
      for (let i = 0; i < data.rows.length; i++) {
        tr = table.insertRow(-1);
        let row = data.rows[i];
        for (let key in row) {
          let tabCell = tr.insertCell(-1);
          tabCell.innerHTML = row[key];
        }
                  
        let tabCell = tr.insertCell(-1);
        tabCell.innerHTML =
          '<input type="button" value="delete" onclick="deleteRow(this)" />';
      }
      // FINALLY ADDING THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
      var divContainer = document.getElementById("showData");
      divContainer.innerHTML = "";
      divContainer.appendChild(table);
    }
    function deleteRow(ele) {
      let data = getData();
      var rowCount = data.rows.length;
      if (rowCount < 1) {
        alert("There is no row available to delete!");
        return;
      }
      if (ele) {
        //delete specific row
        let row = $(ele).closest("tr");
        let dataIndex = row.index() - 1;

        // delete html row
        ele.parentNode.parentNode.remove();
        // delete data from array
        data.rows.splice(dataIndex, 1);
        UpdateLocalStorage(data);
      } else {
        //delete last row
        row.deleteRow(rowCount - 1);
      }
    }
    function getData() {
      return JSON.parse(localStorage.getItem("localData"));
    }
    function UpdateLocalStorage(data) {
      localStorage.setItem("localData", JSON.stringify(data));
    }
  </script>
</html>
Posted
Updated 15-Aug-22 23:04pm
v3
Comments
Richard Deeming 16-Aug-22 3:47am    
You seem to have forgotten to ask a question. You've just dumped your assignment instructions and your entire code file, without explaining what the problem is, what you have tried, or where you are stuck.

Click the green "Improve question" link and update your question to include those missing details.
Abbua7 16-Aug-22 4:05am    
I have updated my question Richard, Thank you for the suggestion.
Chris Copeland 16-Aug-22 4:21am    
I wouldn't say you've improved your question much, you've not told us what's happening, what you expect to happen. What is it you're confused about? Also, have you done any debugging of the code[^] to see what's happening?
Abbua7 16-Aug-22 5:56am    
I want to read previously stored array if there are any if not then initialise a blank array.

I want to update/Store the array in LocalStorage.

I want to know if these 2 operations are being executed or not, that's my doubt on this
Chris Copeland 16-Aug-22 6:52am    
Then I suggest you take a look at the link I provided, this is where debugging comes in. As a developer you'll need to learn to run and debug your code, as in step through the code line-by-line and inspect the variables to see what's happening. If there are errors then it should show in your developer console window.

As for checking local storage, under Chrome you can open your developer tools, navigate to the Application tab, then find and expand the Local Storage option and there should be an entry in there to be able to see your local storage.

We can't validate if this code works for you, you'll need to do that part of the work yourself. We can only advise if you know there's something wrong with the code and can give us the information we need to be able to provide advice.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900