Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

javascript - LocalStorage set and get using select2 multiple

I'm having a trouble on how can I save and get multiple list in localStorage and retain data to my select. I tried to set and get the item but when the page reload the data does not retain in my select. I also tried printing the list through console.log as you can see in the image the localStorage contain list value . The only problem I encountered , it does not retain the multiple data in my select when reloads. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance!

References:link1

enter image description here enter image description here

let data = [{"id":1,"name":"USA","parentid":0},
    {"id":2,"name":"Japan","parentid":0},
    {"id":3,"name":"Europe","parentid":0},
    {"id":4,"name":"California","parentid":1},
    {"id":5,"name":"Oklahoma","parentid":1},
    {"id":6,"name":"Arizona","parentid":1},
    {"id":7,"name":"Kant?","parentid":2},
    {"id":8,"name":"Kansai","parentid":2},
    {"id":9,"name":"Chügoku","parentid":2},
    {"id":10,"name":"France","parentid":3},
    {"id":11,"name":"Deutschland","parentid":3},
    {"id":12,"name":"Espana","parentid":3},
    {"id":13,"name":"Sacramento","parentid":4},
    {"id":14,"name":"Los Angeles","parentid":4},
    {"id":15,"name":"San Diego","parentid":4},
    {"id":16,"name":"Tulsa","parentid":5},
    {"id":17,"name":"Oklahoma City","parentid":5},
    {"id":18,"name":"Lawton","parentid":5},
    {"id":19,"name":"Phoenix","parentid":6},
    {"id":20,"name":"Flagstaff","parentid":6},
    {"id":21,"name":"Tucson","parentid":6},
    {"id":21,"name":"Tokyo","parentid":7},
    {"id":22,"name":"Chiba","parentid":7},
    {"id":23,"name":"Tochigi","parentid":7},
    {"id":24,"name":"Kyoto","parentid":8},
    {"id":25,"name":"Osaka","parentid":8},
    {"id":26,"name":"Nara","parentid":8},
    {"id":27,"name":"Tottori","parentid":9},
    {"id":28,"name":"Hirochima","parentid":9},
    {"id":29,"name":"Okayama","parentid":9},
    {"id":30,"name":"Quimper","parentid":10},
    {"id":31,"name":"Toulouse","parentid":10},
    {"id":32,"name":"Nancy","parentid":10},
    {"id":33,"name":"Dusseldorf","parentid":11},
    {"id":34,"name":"Leipzig","parentid":11},
    {"id":35,"name":"Munchen","parentid":11},
    {"id":36,"name":"Barcelona","parentid":12},
    {"id":37,"name":"Sevilla","parentid":12},
    {"id":38,"name":"Guernica","parentid":12}]

 function populateList(list, props) {
        if(props[0].value != -1){
let l = document.getElementById(list);
          l.innerHTML = "";
          let topItem = document.createElement("option");
          topItem.value = -1;
          topItem.text = "--Select--";
          l.appendChild(topItem); 

          for(let i=0; i< props.length; i++){
            let newOptGroup = document.createElement("optgroup");
            let item = props[i];

            let items = data.filter(it =>  it.parentid == item.value);
            items.forEach(function(it){
                let newItem = document.createElement("option");
                newItem.value = it.id;
                newItem.text = it.name;
                if(props.length>0 && props[0].value !=0){
                    newOptGroup.label= item.key
                    newOptGroup.appendChild(newItem)
                }
                else l.appendChild(newItem);
            })

            if(props.length>0 && props[0].value !=0 && props[0].value !=-1){
                l.appendChild(newOptGroup)
            }
          }
        }

    }

    function updateList(selList, thisList) {
        let values = [];
        for(let i=0;i<thisList.selectedOptions.length; i++) values.push({
            key: thisList.selectedOptions[i].label,
            value: parseInt(thisList.selectedOptions[i].value)
        })

      if (values.length>0 && values[0] != 0) {
        populateList(selList, values);
      } else {
        let s = document.getElementById(selList);
        s.value = "";
        triggerEvent(s, "onchange");
        let sCopy = s.cloneNode(false);
        let p = s.parentNode;
        p.replaceChild(sCopy, s);
      }
    }
    function triggerEvent(e, trigger)
    {
        if ((e[trigger] || false) && typeof e[trigger] == 'function')
        {
            e[trigger](e);
        }
    }
     

    function loadList1() {
      populateList("province[]", [{key: '', value: 0}]);
    }
    window.onload = loadList1;



    function reload_and_saveLocalStorage(){
        
        savedlocalStorage();
        gettingLocalStorage();
        //reload page
        window.location.reload(true);

    }

    function savedlocalStorage(){
        //province setting item to LocalStorage
        const province_options = document.getElementById('province[]').options;
        var prov_selected = [];
        Array.from(province_options).map((option) => {
        if (option.selected) {
        prov_selected.push(option.value);
        }
        });
        localStorage.setItem("province_localstorage", JSON.stringify(prov_selected));

        //municipality setting item to LocalStorage
        const muni_options = document.getElementById('municipality[]').options;
        var muni_selected = [];
        Array.from(muni_options).map((option) => {
        if (option.selected) {
        muni_selected.push(option.value);
        }
        });
        localStorage.setItem("muni_localstorage", JSON.stringify(muni_selected));


        //barangay setting item to LocalStorage
        const barangay_options = document.getElementById('barangay[]').options;
        var barangay_selected = [];
        Array.from(barangay_options).map((option) => {
          if (option.selected) {
            barangay_selected.push(option.value);
          }
        });
        localStorage.setItem("barangay_localstorage", JSON.stringify(barangay_selected));
    }
    function gettingLocalStorage(){

        //Province getting item to Localstorage and display to select
        var province_selected = JSON.parse(localStorage.getItem("province_localstorage"));
        const province_options = document.getElementById('province[]').options;
        Array.from(province_options).map((option) => {
        if(province_selected.indexOf(option.value) !== -1) {
            option.setAttribute("selected", "selected");
        }
        });
        $(".prov").change();

        //Municipality getting item to Localstorage and display to select
        var muni_selected = JSON.parse(localStorage.getItem("muni_localstorage"));
        const muni_options = document.getElementById('municipality[]').options;
        Array.from(muni_options).map((option) => {
        if(muni_selected.indexOf(option.value) !== -1) {
            option.setAttribute("selected", "selected");
        }
        });
        $(".muni").change();


        //barangay getting item to Localstorage and display to select
        var barangay_selected = JSON.parse(localStorage.getItem("barangay_localstorage"));
        const barangay_options = document.getElementById('barangay[]').options;
        Array.from(barangay_options).map((option) => {
        if(barangay_selected.indexOf(option.value) !== -1) {
            option.setAttribute("selected", "selected");
        }
        });
        $(".brgy").change();
    }
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
Region: <select  class = "prov" id="province[]" onchange="updateList('municipality[]', this);" multiple="multiple"></select>
    Sub-region:<select  class="muni" id="municipality[]" onchange="updateList('barangay[]', this);" multiple="multiple"></select>
    Location:<select  class="brgy" id="barangay[]" multiple="multiple"></select>
    <button  onclick="reload_and_saveLocalStorage()">SAVE AND RELOAD </button>
question from:https://stackoverflow.com/questions/65916613/localstorage-set-and-get-using-select2-multiple

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Can't execute the snippet beacuse is not secure envolving localStorage, but my advice is to try

$(".brgy").val(option.value);

Instead of setting the "selected" attribute on the option.

That should work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...