Skip to content

Instantly share code, notes, and snippets.

@jpetto
Created February 24, 2012 21:19
Show Gist options
  • Save jpetto/1903811 to your computer and use it in GitHub Desktop.
Save jpetto/1903811 to your computer and use it in GitHub Desktop.
store/retrieve multiple select values to/from localstorage
// 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;
}
}
});
}
@hakeempazhu
Copy link

Add

$("#motivations").select2();

After the code to Reflect it on Select2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment