- Published on
Day15: LocalStorage
- Authors

- Name
- irisjustdoit
- @irisjustdoit
Introduction: How to use LocalStorage for data storage and management.
Project Page: https://iris1114.github.io/javascript30/15_LocalStorage/
HTML
- Contains a title 'LOCAL TAPAS'
- A
ullist for displaying items, initially showing 'Loading Tapas...' - A form with an input field and submit button for adding new items
<div class="wrapper">
<h2>LOCAL TAPAS</h2>
<p></p>
<ul class="plates">
<li>Loading Tapas...</li>
</ul>
<form class="add-items">
<input type="text" name="item" placeholder="Item Name" required />
<input type="submit" value="+ Add Item" />
</form>
</div>
JavaScript
- Retrieves stored items from LocalStorage and parses them into a JavaScript array
- Defines
addItemfunction to handle form submission events, adding new items to the array and updating LocalStorage - Defines
populateListfunction to render items to theullist
const addItems = document.querySelector('.add-items')
const itemsList = document.querySelector('.plates')
const items = JSON.parse(localStorage.getItem('items')) || []
function addItem(e) {
e.preventDefault()
const text = this.querySelector('[name=item]').value
const item = {
text,
done: false,
}
items.push(item)
populateList(items, itemsList)
localStorage.setItem('items', JSON.stringify(items))
this.reset()
}
function populateList(plates = [], platesList) {
platesList.innerHTML = plates
.map((plate, i) => {
return `
<li>
<input type="checkbox" data-index=${i} id="item${i}" ${plate.done ? 'checked' : ''} />
<label for="item${i}">${plate.text}</label>
</li>
`
})
.join('')
}
addItems.addEventListener('submit', addItem)
populateList(items, itemsList)
Note
- Uses
localStorage.setItemandlocalStorage.getItemfor storing and retrieving data - Uses
JSON.stringifyandJSON.parsefor data serialization and deserialization - Form resets after submission
