So I have this code to store the selections of the Select2 widget in my Local Storage:
// watch for changes to locations select
$('#locations').change(function() {
var selected = []; // create an array to hold all currently selected locations
// loop through each available location
$('#locations 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('locations', JSON.stringify(selected));
});
The problem is that this is my HTML generated by Django:
<select name="preferred_location_test" id="locations" multiple="">
<option value="7">The Netherlands</option>
<option value="9">France</option>
</select>
So I my local storage I get "7" and "9", but I want this to be the option text, so "The Netherlands" or "France". How can I apply this to my code? I am not very good with JavaScript. I tried these SO posts:
Get selected option text with JavaScript
Retrieving the text of the selected <option> in <select> element
But they use selectIndex, and I am not sure how I can use that in my code.
Can somebody help?