Search code examples
javascriptjqueryhtmlajaxsession-storage

How can I store options tags in sessionStorage?


This is my HTML:

<select>
   <option value="val1">Text1</option>
   <option value="val2">Text2</option>
   <option value="val3">Text3</option>
   <option value="val4">Text4</option>
</select>

It is being dynamically populated via $.ajax()

I need to make a function that will place "val" in key and Text in "value" in the sessionStorage, as the object reference. How can I achieve this?

How would it be iterated via index?

My try:

document.getElementsByClassName('next')[0].addEventListener('click', function() {
    sessionStorage.setItem(option.value, option.innerText);
});

.addEventListener() is not firing at all . . . why?

Also, I need it loaded afterwards. How do I do it? Do I use .trigger()?


Solution

  • Just like this:

    var btn = document.querySelector(".next");
    var test = document.querySelector(".test");
    
    btn.addEventListener("click", function(){
      // Get a reference to the select's options
      var options = document.querySelectorAll("option");
    
      // Loop through the options and store the value and text in sessionStorage:
      for(var i = 0; i < options.length; ++i){
        sessionStorage.setItem(options[i].getAttribute("value"), options[i].textContent);
      }
    });
    
    test.addEventListener("click", function(){
    
      // Now, just to show how to get the values out of sessionStorage:
      for (var i = 0; i < sessionStorage.length; i++){
        alert(sessionStorage.getItem(sessionStorage.key(i)));
      }
    
    });
    <select>
       <option value="val1">Text1</option>
       <option value="val2">Text2</option>
       <option value="val3">Text3</option>
       <option value="val4">Text4</option>
    </select>
    <button class="next">Next</button>
    
    <button class="test">Test</button>

    This code won't work, here in the Stack Overflow snippet environment, but you can see it work here.