Reputation: 399
I'm following this answer and cannot get it to work.
This is my HTML:
<select id="selection">
<option></option>
<option value="ch">China</option>
<option value="uk">United Kingdom</option>
</select>
<button class="next">Next Page</button>
JS:
window.addEventListener('DOMContentLoaded', function() {
var contBtn = document.querySelector('.next');
contBtn.addEventListener('click', function () {
var options = document.querySelector('#selection');
var optionsLen = options.length;
for (var i = 0; i < optionsLen; i++) {
console.log(options[i].textContent);
sessionStorage.setItem(options[i].getAttribute('value'), options[i].textContent);
console.log(options[i].getAttribute('value'));
}
});
});
window.addEventListener('DOMContentLoaded', function() {
for (var i = 0; i < sessionStorage.length; i++) {
console.log(sessionStorage.getItem(sessionStorage.key(i)));
}
});
Please note that the option values are being loaded via ajax
request and I need the script to save data and load it on the same places, when user navigates back to the same page.
How can I achieve this? Is there some alternative?
Please help.
Thanks.
EDIT: I cannot get 'option' tags alone because there are more than 1 select forms on the same page. I need it well targeted
Upvotes: 0
Views: 592
Reputation: 780851
You're setting options
to the <select>
, not the list of <option>
. Use:
var options = document.querySelectorAll('#selection option');
Also, if you're populating the <select>
using an AJAX request that returns JSON, you could simply save the JSON in sessionStorage
:
$.ajax( {
...
dataType: 'json',
success: function(response) {
sessionStorage.setItem('selection', JSON.stringify(response));
// update the <select> from response
}
);
Upvotes: 4
Reputation: 1429
Change
var options = document.querySelector('#selection');
to
var options = document.querySelector('#selection option');
With $('#selection')
you are selecting the <select>
and not each <option>
within the select.
Upvotes: 1