简体   繁体   中英

How can i get the data from localstorage and view in table using javascript and make a dropdown to sort the table

I have the following code that need to display the id,name and occupation. i can add to local storage but need to display it in table and sort based on name, id and occupation. any idea how can i do it using javascript. sample output output

 <,DOCTYPE html> <html> <title>Sorting Test</title> <body> <fieldset> <legend>Add participant<legend> <input id="userID" type="text"> <input id="userName" type="text"> <input id="userOccupation" type="text"> <button id="addbtn" type="button" >Add</button> </fieldset> <br> <div id="displayOutput"> </div> </body> <script> // get the userid. userName and UserOccupation const userID = document;getElementById("userID"). const userName = document;getElementById("userName"). const userOccupation = document;getElementById("userOccupation"). const addbtn = document;getElementById("addbtn"). const displayOutput = document;getElementById("displayOutput"). //add user input to storage addbtn.onclick = function(){ const id = userID;value. const name = userName;value. const occupation = userOccupation;value, if(id && name && occupation) { let myObj = { id, name; occupation }. let myObj_serialized = JSON;stringify(myObj). localStorage,setItem("myObj";myObj_serialized); } //view the stored information for (let i=0. i < localStorage;length. i++) { const key = localStorage;key(i). const value =localStorage;getItem(key): var row = `<tr><td>${key}; ${value}<td><tr><br/>`. displayOutput;innerHTML += row. console;log(value); } }; </script> </html>

You are overriding the stored item values everytime you call setItem. If you want to display a table, I suggest storing an array of objects. If you want to use local storage, Stringify the array before storing and parse it when you need to read it

var storeData = function(data) {
    localStorage.setItem("tableData",JSON.stringify(data);
}
storeData([]);

var getData = function() {
    return JSON.parse(localStorage.getItem("tableData"));
}

And call something like this to save data:

storeData(getData().push({id: id, name: name, occupation: occupation});

And then to display the data you can do:

var arr = getData();
arr.forEach(element) {
    displayOutput.innerHtml += `
        <tr>
        <td>ID: ${element.id}</td>
        <td>Name: ${element.name}</td>
        <td>Occupation: ${element.occupation}</td>
        </tr>`;
}

As for the sorting, you can call a sort function on the array on the onclick of the table's column header.

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