I'm having trouble figuring out how to use session storage for list items. This doesn't seem to be working and because of the styling, I can't use the basic select/option:
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"><span data-bind="label">Day</span><span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" name="country">
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
</ul>
var item = window.localStorage.getItem('country');
$('ul[name=country]').val(item);
$('ul[name=country]').change(function() {
window.localStorage.setItem('country', $(this).val());
});
You're trying to use val
in a ul
tag, and it does not have value
property.
Also, you're trying to use a change
event on it, and it does not have that event either.
First, you must understand what you're doing there. You've probably copied this Dropdown Picker from anywhere else, and you don't understand what it's doing.
It's simulating a select
behavior by using a label
inside a button
, and anytime a li
inside the ul
tag is clicked, your code changes the label
text to the li
's one.
So, firstly, when your page is loaded, you must see if anything is already in your localStorage, and if it is, you must change the label's text to the value saved in the localStorage.
var item = localStorage.getItem('country');
if (item) $('span[data-bind="label"]').text(item);
After that, inside your li
's click event, you must save the clicked li
's text into the localStorage for persisting purposes later.
// Dropdown picker
$('.dropdown-menu').on('click', 'li', function(e) {
var $target = $(e.currentTarget);
/* the rest of your code */
localStorage.setItem('country', $target.text());
});
I've updated your fiddle with the code working.