简体   繁体   中英

How to store data in Array using Local storage in HTML?

    <!DOCTYPE html>
<html>
<body>
<input type="text" id="textstorage">
<button name="testbutton" onclick="myFunction()">send</button>
<div id="result"></div>

<script>
function myFunction(){
alert("dasd")
// Check browser support
var inp = document.getElementById("textstorage");
if (typeof(Storage) != "undefined") {
    // Store
    localStorage.setItem("result", inp.value);
    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("result");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
}

document.getElementById("result").innerHTML = localStorage.getItem("result");



</script>

</body>
</html>

How to store multiple values in webpage using Array. Please help me.

Note: If i enter one value it replaces the previous value. I need like array stores all values.

LocalStorage does not support arrays but only string values. It stores key:value pairs. Use JSON.stringify() and JSON.parse() to store arrays indirectly in a LocalStorage object.

For Example:

var arr = new Array();
arr[0] = "One";
arr[1] = "Two";
arr[2] = "Three";

localStorage["arr"] = JSON.stringify(arr);
var arrStored = JSON.parse(localStorage["arr"]);

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