wickywills
9/6/2017 - 1:15 PM

Checkbox values into local storage

Checkbox values into local storage

Local storage

For a client site, I needed to store the values of which brochures where 'checked' so that I could build up a list of brochures (almost like a shopping cart) which the user could request. Since this needed to happen along with pagination, I decided to use local storage:

HTML

<input type="checkbox" 
class="faChkRnd" id="like1" />
<input type="checkbox" 
class="faChkRnd" id="like2" />
<input type="checkbox" 
class="faChkRnd" id="like3" />

Javascript (jQuery)

/**
 * Firstly, the checkboxes need to remain in their checked/unchecked state 
 * between pages (or refresh). Localstorage takes care of this.
 */
jQuery('.brochure-select-checkbox').on('change', function () {

    // Serialised arrays of the checkboxes
    var brochureArrs = []; 

    // Get current page number
    var pageNumber = {{ pageNumber }};

    // Add the data from every checkbox to the brochureArrs array
    jQuery('.brochure-select-checkbox').each(function () {
        var brochure = {
            id: jQuery(this).attr('id'),
            checked: jQuery(this).prop('checked'),
            value: jQuery(this).val()
        };

        brochureArrs.push(brochure);
    });

    // Add the current brochure to the array of brochures
    brochureArrs.push(brochure);

    // Save the serialised array to local storage for use later even when on another page
    localStorage.setItem("brochureArrs" + pageNumber, JSON.stringify(brochureArrs));

    getBrochures();
});

/**
 * Second, retrieve the information of the state of the brochures from localstorage
 * and retrieve the values (which in this case is the human-readable name).
 */
jQuery(document).ready(function () {

    // Get current page number
    var pageNumber = {{ pageNumber }};

    // Retrieve local storage
    var brochureArrs = JSON.parse(localStorage.getItem('brochureArrs' + pageNumber));

    // If the array is empty, do nothing
    if (!brochureArrs.length) {
        return;
    }

    // Update the 'checked' state of each brochure from the values in local storage
    for (var i = 0; i < brochureArrs.length; i++) {
        jQuery('#' + brochureArrs[i].id).prop('checked', brochureArrs[i].checked);
    }

    getBrochures();
});

/**
 * Lastly, send the names of the brochures over to a hidden field on the 
 * contact form so it can be sent onto the client.
 */
function getBrochures() {

    // Get current page number
    var pageNumber = {{ pageNumber }};

    // Retrieve local storage
    var brochureArrs = JSON.parse(localStorage.getItem('brochureArrs' + pageNumber));

    var pageKeys = Object.keys(localStorage).filter(key => key.indexOf('brochureArrs') === 0);
    var values = Array.prototype.concat.apply([], pageKeys.map(key => JSON.parse(localStorage[key])));
    console.log(values);

    // Create an empty array to store the values
    var brochureValues = [];

{#  for (var i = 0; i < pageKeys.length; i++) {
        if (brochureArrs[i].checked == true) {
            console.log("checked");
            brochureValues.push(brochureArrs[i].value);
        }
    }#}

    values.forEach(function(key,index) {
        // key: the name of the object key
        // index: the ordinal position of the key within the object 
        if(key.checked == true){
            brochureValues.push(key.value);
        }
    });

    // Update the hidden field with the currently selected brochures
    jQuery('#brochuresRequested').val(brochureValues.join(", "));

    // Visual list for user of selected brochures
    jQuery('#brochuresselected').html(brochureValues.join(", "));
} // getBrochures()