简体   繁体   中英

Printing JSON in HTML TABLE saved from another table using local storage so that i print my table on another page

In my assignment i have to take the data from user input using and save data in local storage. I have to print this data from local storage in horizontal table format to other pages.For this i made the code for user input and saving data in local storage

<style>
        data {
            color: #138bc2;
        }
    </style>
    <body>
   <script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
   <div id="POItablediv">
   <p>
   <input type="button" id="bt" value="Submit Data" onclick="submit()" />
   </p>
   <input type="button" onclick="insRow()" id="addPOIbutton" value="Add values"/><br/><br/>
   <table id="POITable" border="1">
   <thead>
       <tr>
           <td>WEEK NO</td>
           <td>Daily exercise</td>
           <td>calorie</td>
           <td>food</td>
            <td>Revision no</td>
           <td>Delete?</td>

       </tr>
       </thead>
       <tbody>
       <tr>
           <td><input size=25 type="text" id="weekbox"/></td>
           <td><input size=25 type="text" id="latbox"/></td>
           <td><input size=25 type="text" id="lngbox"/></td>
           <td><input size=25 type="text" id="lnbox"/></td>
           <td><input size=25 type="text" id="lntbox"/></td>
           <td><input type="button" id="delPOIbutton" value="Delete" onclick="deleteRow(this)"/></td>

       </tr>
       <tbody>
   </table>
   </body>
   <script>
   function deleteRow(row)
    {
        var i=row.parentNode.parentNode.rowIndex;
        if(i>1){
        document.getElementById('POITable').deleteRow(i);
        }

    }


    function insRow()
    {

        var x=document.getElementById('POITable');
        var new_row = x.rows[1].cloneNode(true);
        var len = x.rows.length;
        new_row.cells[0].childNodes[0].value = "";

        var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
        inp1.id += len;
        inp1.value = '';
        var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
        inp2.id += len;
        inp2.value = '';
        x.appendChild( new_row );
        var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
        inp3.id += len;
        inp3.value = '';
        var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
        inp4.id += len;
        inp4.value = '';
        x.appendChild( new_row );
    }
   function submit() 
   {
     var table = document.getElementById("POITable")
     var tableLen = table.rows.length           
     var data = {labels: [], alpha: [], beta: [],gamma:[]}

   for (var i = 1; i < tableLen; i++) 
  {
     data.labels.push(table.rows[i].cells[0].childNodes[0].value)
     data.alpha.push(table.rows[i].cells[1].childNodes[0].value)
     data.beta.push(table.rows[i].cells[2].childNodes[0].value)
     data.gamma.push(table.rows[i].cells[3].childNodes[0].value)
  }
 var alphadata = data
localStorage.setItem("quant", JSON.stringify(alphadata));

above code is for taking input from user and saved in local storage.My aim is to print data from local storage to another page in vertical header I mean that the table has the header () tag on the left side (generally).

e<body>
<input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
<p id="showData"></p>
 </body>

<script>
function CreateTableFromJSON() {
    var myBooks =JSON.parse(localStorage.getItem("quant"));

    var col = [];
    for (var i = 0; i < myBooks.length; i++) {
        for (var key in myBooks[i]) {
            if (col.indexOf(key) === -1) {
                col.push(key);
            }
        }
    }

    // CREATE DYNAMIC TABLE.
    var table = document.createElement("table");

    // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

    var tr = table.insertRow(-1);                   // TABLE ROW.

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

    // ADD JSON DATA TO THE TABLE AS ROWS.
    for (var i = 0; i < myBooks.length; i++) {

        tr = table.insertRow(-1);

        for (var j = 0; j < col.length; j++) {
            var tabCell = tr.insertCell(-1);
            tabCell.innerHTML = myBooks[i][col[j]];
        }
    }

    // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
    var divContainer = document.getElementById("showData");
    divContainer.innerHTML = "";
    divContainer.appendChild(table);
    }
    </script>
    </html>

Table is not printing when i click on button in second page. its gives me blank page. Any lead would be appreciated.

So I did not find a problem with the first file that inserts the JSON data to the local storage. The problem was with getting the data from the second file

<html>

<body>
    <input type="button" onclick="CreateTableFromJSON()" value="Create Table From JSON" />
    <p id="showData"></p>
</body>

<script>
    function CreateTableFromJSON() {
        var myBooks = JSON.parse(localStorage.getItem("quant"));
        console.log(myBooks);
        /* This logs the object to confirm whether it is there and to 
        confirm the values inside it You should make this a habit
        so that you can check for errors*/

        // var col = [];
        // for (var i = 0; i < myBooks.length; i++) {
        //     for (var key in myBooks[i]) {
        //         if (col.indexOf(key) == -1) {
        //             col.push(key);
        //         }
        //     }
        // }
        /* The code above is the one I have commented out and replaced with
        the one below to get both the keys and values in separate arrays */

        col_keys = Object.keys(myBooks);
        // Object.keys gets the keys of the object
        col_values = Object.values(myBooks);
        // Object.values gets the values in an object

        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.

        var tr = table.insertRow(-1);                   // TABLE ROW.

        /* --- REFERENCE 1 --- The length of col_keys and col_values is the same because they
        are key and value pairs */

        for (var i = 0; i < col_keys.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col_keys[i];
            /* col_keys has the keys of the object which are added to
            the table header */
            tr.appendChild(th);
        }

        // ADD JSON DATA TO THE TABLE AS ROWS.

        for (var i = 0; i < col_values[0].length; i++) {

            /* The loop runs as many times as the number of items in each array
            EXPLANATION: col_values contains arrays.
            col_values[0].length returns the length of the first array, which is
            the array that contains the labels.
            And since all the arrays have the same length whether they have a value
            or not, the length of the first array is the same for all the others. 
            --- REFERENCE 2 --- In this case this outer loop runs 2 times*/

            tr = table.insertRow(-1);

            for (var j = 0; j < col_values.length; j++) {
                /* The inner loop runs as many times as the number of key-value pairs
                in the object.
                EXPLANATION: As " --- REFERENCE 1 --- " above says, this will run **4** times
                based on your current object which has:
                1.labels
                2.alpha
                3.beta
                4.gamma
                */
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = col_values[j][i];
                /* Each time the loop runs, it inserts the "i" value of the array
                of each of the values of the object.
                Check " --- REFERENCE 2 --- " ... since "i" is less than the length
                of each array, it will only run as many times as the number of values
                in the array.
                In this case **2** times.
                */
            }
        }

        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("showData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
</script>

</html>

There are comments everywhere so make sure to read them and understand why it works that way. Because this is also a learning process. If you have a question just ask.

This code implements another function to create a horizontal format. Please read the comments and also try to understand it so that it can help you in the future

<html>

<body>
    <input type="button" onclick="createHorizontal()" value="Create Table From JSON" />
    <p id="showData"></p>
    <div id="horizontal"></div>
</body>

<script>

    function createHorizontal(){
        var myBooks = JSON.parse(localStorage.getItem("quant"));
        console.log(myBooks);

        col_keys = Object.keys(myBooks);
        // Object.keys gets the keys of the object
        col_values = Object.values(myBooks);
        // Object.values gets the values in an object

        var final_array = [];
        /* Here is the final array that will hold all the data */

        for(var i = 0; i < col_keys.length; i++){
            var inner = [];
            // The inner array that will be pushed with a new value
            // after every loop

            inner.push("<div class='main'>");
            inner.push("<li>" + col_keys[i] + "</li>");
            for(var j = 0; j < col_values[0].length; j++){
                inner.push("<li>" + col_values[i][j] + "</li>");
            }
            inner.push("</div>");

            //The above code creates the html for each of the rows

            inner = inner.join("");
            // To remove the commas from the final array
            final_array.push(inner);
        }
        console.log(final_array);

        var elem = document.getElementById("horizontal");
        var final_div = [];

        final_div.push("<div class='container'>");
        for(var n = 0; n < final_array.length; n++){
            final_div.push(final_array[n]);
        }
        final_div.push("</div>");

        // The above code creates the html for the whole div block

        final_div = final_div.join("");
        // To remove the commas
        console.log(final_div);

        elem.innerHTML = "";
        elem.innerHTML = final_div;
    }
</script>
<style>
    .container {
        display: flex;
        flex-direction: column;
        /* Make the rows stack on top of each other */
    }

    .main {
        display: flex;
        flex-direction: row;
        /* Make the elements in the div stack side by side */
    }

    .main li {
        list-style-type: none;
        padding: 5px 10px;
        width: 50px;
    }

    .main li:first-of-type {
        font-weight: bold;
        background-color: #222222;
        color: #ffffff;
    }
</style>

</html>

It also uses CSS to make the elements appear in that format or else it would look different. I advise you to analyze and understand it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM