Created
February 24, 2012 21:19
-
-
Save jpetto/1903811 to your computer and use it in GitHub Desktop.
store/retrieve multiple select values to/from localstorage
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// watch for changes to motivations select | |
$('#motivations').change(function() { | |
var selected = []; // create an array to hold all currently selected motivations | |
// loop through each available motivation | |
$('#motivations option').each(function() { | |
// if it's selected, add it to the array above | |
if (this.selected) { | |
selected.push(this.value); | |
} | |
}); | |
// store the array of selected options | |
localStorage.setItem('motivations', JSON.stringify(selected)); | |
}); | |
// check for stored motivations | |
var stored_motivations = JSON.parse(localStorage.getItem('motivations')); | |
if (stored_motivations !== null) { | |
$('#motivations option').each(function() { | |
for (var i = 0; i < stored_motivations.length; i++) { | |
if (this.value == stored_motivations[i]) { | |
this.selected = true; | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add
$("#motivations").select2();
After the code to Reflect it on Select2