Skip to content

Save multiple values to same type in LocalStorage then retrieve the values

My main requirement is to generate a URL by clicking on the relevant button. For example If I click on the green and red button then it should append &_colour=green%2Cred in the url and similar for Gender’s button after saving and getting values from localStorage.

<div class="main-section">
    <div class="section">
        <button data-gender="men">Men</button>
        <button data-gender="women">Women</button>
    <div class="section">
        <button data-colour="green">green</button>
        <button data-colour="red">Red</button>
jQuery('.section button').click(function(e){
    var gender = jQuery(this).data("gender");
    var colour = jQuery(this).data("colour");
    localStorage.setItem("gender", gender);
    var x = localStorage.getItem("gender");

The question is how to save multiple values against the same type and retrieve the values to create the url.

Thanks in Advance.


To retrieve multiple values you need to loop through all the buttons in the page and find the ones which have been clicked on. You can toggle a class on the buttons when they are clicked in order to identify them more easily.

From there you can use a loop to build an object from the selected values, adding a new data-category attribute to the .section elements to provide the keys in that object.

Finally you can use a URLSearchParams object to build the updated querystring from that object before applying that to history.pushState() to update the current URL.

Put all that together and you get this:

<script src=""></script>
<div class="main-section">
  <div class="section" data-category="gender">
    <button data-value="men">Men</button>
    <button data-value="women">Women</button>
  <div class="section" data-category="colour">
    <button data-value="green">green</button>
    <button data-value="red">Red</button>
jQuery($ => {
  let $buttons = $('.section button').click(e => {
    let data = buildButtonDataObject();
    let querystring = new URLSearchParams(data).toString();
    localStorage.setItem('data', data);
    history.pushState(data, 'Page title here', querystring);
let buildButtonDataObject = () => {
  let obj = {};
  $('.section:has(.active)').each((_, s) => obj[s.dataset.category] = $(s).find('').map((_, b) => b.dataset.value).get());
  return obj;

Working example

In the jsFiddle example, you can see the querystring being updated as you click the buttons by opening the ‘Network’ panel in dev tools.