HTML Web Storage
HTML5 provides two mechanisms for storing data on the client-side: localStorage and sessionStorage. These allow web developers to store and retrieve data without having to rely on cookies or server-side storage.
Here's an example of using localStorage to store data:
html
<input type="text" id="myinput">
<button onclick="saveData()">Save Data</button>
<script>
function saveData() {
var input = document.getElementById("myinput").value;
localStorage.setItem("mydata", input);
}
</script>
In this example, an input field and a button are used to allow the user to enter data and save it to localStorage. The saveData() function retrieves the data from the input field and saves it to localStorage under the key "mydata".
To retrieve the saved data, you can use the following code:
html
<p>Saved data: <span id="savedata"></span></p>
<script>
var savedata = document.getElementById("savedata");
savedata.innerHTML = localStorage.getItem("mydata");
</script>
In this example, a paragraph element with an empty <span> element is used to display the saved data. The localStorage.getItem() method retrieves the data from localStorage under the key "mydata" and sets the text content of the <span> element to the retrieved data.
sessionStorage works in a similar way to localStorage, but the data is only available for the duration of the browser session.
No comments:
Post a Comment