husin.anti husin.anti - 1 year ago 117
Javascript Question

HTML5: Using array on Local Storage

I have this code :

<script type="text/javascript" >
// fungsi simpan(), ketika tombol diklik maka string
// di dalam input akan tersimpan ke dalam storage browser
function simpan() {
var storage = document.getElementById('nama').value;
// tampil() akan menampilkan string yang tersimpan
// ke tag div yang ditentukan "hasil"
function tampil() {
var tampilNama = localStorage.getItem('Text');
if (tampilNama) {
x = document.getElementById('tampil');
// fungsi untuk menghapus localstorage browser
function hapus() {
<input type="text" id="nama" />
<input type="button" value="Simpan" onclick="simpan()" />
<input type="button" value="Tampil" onclick="tampil()" />
<input type="button" value="Hapus" onclick="hapus()" />
<div id="tampil"></div>

it will show input form and the text would store to local storage, when i press "Tampil" button, the text will showing in
div id="tampil"
, it works for me, but it just one input.

How can i add some array that the text won't replace after i input another text?

Answer Source

For arrays you can use JSON.stringify and JSON.parse to write and read to localStorage:

function simpan() {   
    var storage = localStorage.getItem('Text'); // Get local storage
    if(storage) storage = JSON.parse(storage);  // If it exist parse it
    else storage = [];                          // Otherwise define a empty array
    // Push value to array  
    // Stringify the array into text to store.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download