javascript - Store and retrieve the dynamically populated drop-down list in a localStorage -
i have drop down list populated dynamically. send ajax request , response , based on condition drop-down populated. need store these populated list in localstorage need display values populated on page refresh.
everything works fine except getting last value populated in drop-down list. not values populated previously. need retrieve values populated previously.
index.jsp
<input type="radio" class="radiobutton" value="display all" checked onclick="fncheck();"> display <input type="radio" class="radiobutton" value="display divisions" onclick="fncheck();"> display divisions <input type="radio" class="radiobutton" value="display data" onclick="fncheck();"> display data <select id="convoy_list"> <option>values</option> </select> <input type="button" id="testbtn" value="test" onclick="fnclicktest();" > <input type="button" id="ok" value="ok" onclick="fnok();" > <input type="button" id="refresh" value="refresh" onclick="fndisplay();"
myjs.js
function test(){ $.ajax({ //some requests , data sent //get response success:function(responsedata){ for(i=0;i<responsedata.data;i++): { var unitid=//some value ajax response if(somecondition) { var select=$(#convoy_list); $('<option>').text(unitid).appendto(select); var conarr=[]; conarr=unitid; test=json.stringify(conarr); localstorage.setitem("test",test); } } } }); }
in function display() try retrieving localstorage values
function display(){ if(localstorage.getitem("test")){ var listid=$(json.parse(localstorage.getitem("test"))); var select=$(#convoy_list); $('<option>').text(listid).appendto(select); }
here if data populated in drop down list c1 c2 , c3 instance. after refresh page c3 populated in drop-down . want values ie c1,c2,c3 populated after refresh. how can achieve this?
as david said overwriting item in localstorage. key name should unique. value of key changing @ every iteration not key name. hence store need use key different names @ each iteration. instead of using
localstorage.setitem("test",test);
use
localstorage.setitem("test"+i,test);
this not overwrite. , while retrieving use in display()
function display(){ for(var i=0;i<localstorage.length;i++){ if(localstorage.getitem("test"+i)){ var listid=$(json.parse(localstorage.getitem("test"+i))); var select=$(#convoy_list); $('<option>').text(listid).appendto(select); } } }
this append values in drop-down list populated.
Comments
Post a Comment