HTML5 local storage - Can i store more than one value per key, if not what alternative i can use?

Viewed 116

I have a page where is the a form a user can submit multiple times through it I want to store every value submitted in a single local storage key but the problem is the key can only store one value and gets overwritten by the next value

IS there any alternative?

1 Answers

Is there any alternative?

Yes. Use a JSON object that you deserialize + edit + reserialize.

Like so:

// 1: Initial save:

const formState = {
    field1: document.getElementById( 'input1' ).value,
    field2: document.getElementById( 'input2' ).value,
    field3: document.getElementById( 'input3' ).value,
    field4: document.getElementById( 'input4' ).value
};

window.localStorage.setItem( "formState", JSON.stringify( formState ) );

(The const keyword means the object reference cannot be reassigned, it does not mean that formState is immutable)


To add a new value to the object, just set it (JavaScript object values are conceptually the same thing as a hashtable/dictionary):

const formState = JSON.parse( window.localStorage.getItem( "formState" ) );

formState.field5 = document.getElementById( 'input5' ).value;

window.localStorage.setItem( "formState", JSON.stringify( formState ) );

To remove an entry from the formState object, use the delete keyword:

const formState = JSON.parse( window.localStorage.getItem( "formState" ) );

delete formState.field3; // This removes 'field3' completely.

window.localStorage.setItem( "formState", JSON.stringify( formState ) );

You can also quickly dump an entire <form> to an object, like so:

// WARNING: This code is a quick-and-dirty demonstration, it is not production-quality. You'll need to sort-out handling of multiple-select <select> elements and other types of <input>, like file inputs.

const formState = {};

const form = document.getElementById( 'myForm' );

const inputs = form .querySelectorAll( 'input[name], select[name], textarea[name]' );

for( const input of inputs ) {
    let shouldInclude = true;
    if( input.tagName == 'INPUT' && ( input.type == 'radio' || input.type == 'checkbox') ) {
        if( input.checked === false ) shouldInclude = false;
    }

    if( shouldInclude ) formState[ input.name ] = input.value;
}

Related