简体   繁体   中英

HTML5 Local Storage store form data for select box where multiple values are selected

I have a form which saves a users preferance in local storage, it can be seen in this fiddle or below .

With what I have so far there are 2 main problems.

  1. On clicking the save button you are meant to empty the myStorage then append what you have just selected in there, so they can see the live result of what they have clicked. It only remembers if you re-run the fiddle.
  2. My biggest problem is that what I have is great for select fields with one option but in this case the user can select multiple, so what do I need to add to it so that the user can save multiple values to local storage so next time they load the page there multiple selections will be saved?

     <form name="Filter"> <select multiple="1" id="filter"> <option value="111">Andrew</option> <option value="222">Bill</option> <option value="333">Charles</option> <option value="444">Dikembe</option> <option value="555">Edward</option> </select> </form> <div id="store">click to store</div> <br> <h3>People I have stored</h3> <div id="myStorage"></div> 

JS

    var iSelectedTitle = localStorage.getItem('title');
    var iSelectedVal = localStorage.getItem('value');
    console.log("iSelectedTitle: " + iSelectedTitle);
    console.log("iSelectedVal: " + iSelectedVal);

    $("#filter option").each(function () {
        if ($(this).val() == iSelectedVal) {
            $(this).attr("selected", "selected");
        }
    });

    $("#store").click(function () {
        var mytitle = $("#filter option:selected").text();
        var storedTitle = localStorage.setItem("title", mytitle);
        console.log("mytitle: " + mytitle);
        console.log("storedTitle: " + storedTitle);

        var myValue = $("#filter option:selected").val();
        var storedValue = localStorage.setItem("value", myValue);
        console.log("myValue: " + myValue);
        console.log("storedValue: " + storedValue);

        if (iSelectedTitle != "undefined") {
            $('#myStorage').empty().append(iSelectedTitle);
        }
    });
    if (iSelectedTitle != "undefined") {
        $('#myStorage').append(iSelectedTitle + ' - <a target= "_blank "href="http://www.example.com/' + iSelectedVal + '">View profile</a>');
    }

You can add multiple options to an array using map of jQuery :

var optArray = $("#filter option:selected").map(function () {
        return {
            "title": this.innerHTML,
            "value": this.value
        }
}).get();

This will give you a nice array like this :

[
    { "title": "Andrew", "value": "111" },
    { "title": "Bill", "value": "222" },
    { "title": "Charles", "value": "333" }
]

For adding to localStorage :

$("#store").click(function () {
    //get the selected options in the form of an array
    var optArray = $("#filter option:selected").map(function () {
        return {
            "title": this.innerHTML,
            "value": this.value
        }
    }).get();
    console.log(optArray);
    //set that to localStorage
    localStorage["optArray"] = JSON.stringify(optArray);
    //refresh myStorage
    getFromStore();
});

For refreshing the myStorage container with your newly added people, you'll have to call this handler as the last event inside the `click event (above).

var getFromStore = function () {
    //check if store values are null, if null, make store =[]
    var store = [undefined, null].indexOf(localStorage["optArray"]) != -1 ? [] : JSON.parse(localStorage["optArray"]);
    console.log(store);
    //empty container before u put values
    $('#myStorage').html('');
    //check if store is empty
    if (store.length != 0) {
        //loop over store if it aint empty and append the content into myStorage div
        for (var k in store) {
            var str = '<div>' + store[k]["title"] + ' - <a target= "_blank" href="http://www.example.com/' + store[k]["value"] + '">View profile</a></div>';
            console.log(store[k]);
            $('#myStorage').append(str);
        }
    } else {
        //do this if no data is found in localStorage
        $("#myStorage").html("No people found in store");
    }
}

Then, in DOM ready , call getFromStore to refresh myContainer on load of the page:

$(function() {
  getFromStore();
})

Demo : http://jsfiddle.net/hungerpain/hqVGS/9/

EDIT

To select the checkboxes by default, add the folowing line in the getFromStore function :

  $("[value=" + store[k]["value"] + "]","#filter").prop("selected", true); //find the option with the corresponding value and select it

Updated demo : http://jsfiddle.net/hungerpain/hqVGS/10/

You could save multiple values in an array,

var myValuesArr = ['one','two','three'];

The array would need to be serialized before it is saved to localStorage

var serialVals = JSON.stringify(myValuesArr);
localStorage.setItem('numbers',serialVals);

Likewise, the stored data will have to be unserialized after it is read back

var serialVals = localStorage.getItem('numbers');
var myValuesArr = JSON.parse(serialVals);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM