HTML5本地存储存储选择框的数据,其中选择了多个值

时间:2013-06-22 09:36:29

标签: javascript jquery html5 forms local-storage

我有一个表单可以将用户优先保存在本地存储中,可以在this fiddle or below中看到。

到目前为止,我有两个主要问题。

  1. 单击“保存”按钮,您将清空myStorage,然后在此处附加您刚刚选择的内容,以便他们可以看到他们点击的实时结果。它只记得你是否重新操作小提琴。
  2. 我最大的问题是我拥有的选项只有一个选项,但在这种情况下,用户可以选择多个,所以我需要添加多少,以便用户可以保存多个值本地存储,以便下次加载页面时会保存多个选项?

    <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>
    
  3. 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>');
        }
    

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery的map向数组添加多个选项:

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

这会给你一个很好的数组:

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

添加到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();
});

要使用新添加的人刷新myStorage容器,您必须将此处理程序称为“click事件(上图)中的最后一个事件。”

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");
    }
}

然后,在DOM ready中,在页面加载时调用getFromStore刷新myContainer

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

演示:http://jsfiddle.net/hungerpain/hqVGS/9/

修改

要默认选中复选框,请在getFromStore功能中添加以下行:

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

更新了演示:http://jsfiddle.net/hungerpain/hqVGS/10/

答案 1 :(得分:1)

您可以在数组中保存多个值,

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

在将数组保存到localStorage

之前,需要对其进行序列化
var serialVals = JSON.stringify(myValuesArr);
localStorage.setItem('numbers',serialVals);

同样,存储的数据在回读后必须进行反序列化

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