Search code examples
javascriptdrop-down-menulocal-storage

Storing multiple select option values in localStorage using select id as key


Context

First off, I am not a developer but I have tried to explain the desired outcome... I want to use Vanilla JS for this solution.

The problem

I have multiple select dropdowns on the page and ideally want to be able to store the value onchange of each of the dropdowns.

<select name="Value1A" id="Value1A" onchange="storeValue()">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<select name="Value1B" id="Value1B" onchange="storeValue()">
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

Essentially I want to achieve this...

This is of course not actual working code but hopefully explains what I am trying to do

function storeValue(){
 localStorage.setItem(select.id, select.value);
}

i.e. I want to use the select id as the localStorage key - and onchange store the value of the option of that select field (onchange).

Any help would be really appreciated. Any questions or need to me to explain better, let me know.


Solution

  • Pass event inside your onclick handler

    it will look like this

    <select name="Value1A" id="Value1A" onchange="storeValue(event)">
      <option value="0">0</option>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
    </select>
    

    After inside your storeValue function get the id from event.target like this

    function storeValue(event){
     localStorage.setItem(event.target.id, event.target.value);
    }