Search code examples
javascripthtmlsession-storage

JavaScript/HTML - Keeping numeric values from select dropdown list selected


I am keeping the values of my option HTML tags selected using this code:

document.getElementById('select_itens_op').onchange = function() {
   sessionStorage.setItem('pagina', document.getElementById('select_itens_op').value);
};

if (sessionStorage.getItem('pagina')) {
   document.getElementById('select_itens_op').options[sessionStorage.getItem('pagina')].selected = true;
}

It was working just fine, but in one of my tags I came across with a problem. The option tags have numeric values and when I reload the page, what it's being kept is the option related to the index of the value stored in the sessionStorage.

Example:

<select name="select_itens_op" id="select_itens_op" ">
   <option value="">Página</option>
   <option value="2">2</option>
   <option value="4">4</option>
   <option value="8">8</option>
   <option value="10">10</option>
</select>

If I select the option with value 2, this value will be stored into the sessionStorage, but when I refresh the page the option selected will be the one with value 4, since it is the position 2 of the list. If I select 4 the value stored will be 4 and the option returned would be 10, and so on.

If I use string values it works great, provided I add ids to these tags, but I need these numeric values. I already made my research and I didn't find a proper answer.

What is the best way to solve this?


Solution

  • Go for SelectElement.value directly:

    const el_op = document.getElementById('select_itens_op');
    
    // Set on init
    if (sessionStorage.pagina) el_op.value = sessionStorage.pagina;
    // Store on change
    el_op.addEventListener('change', () => sessionStorage.pagina = el_op.value );