javascripthtmlfunctiondebugginglocal-storage

How to add multiple values to a key in local storage


Im trying to allow a user to select multiple select options that can be stored in local storage. Trying to allow users to choose multiple select options that get saved and are displayed on screen.

html

   <body>
    <div class="custom_tunings">
        <h1>Custom Tunings</h1>
        <br>
        <fieldset>
            <legend>Add New Tunings</legend>
            <div class="formBox">
                <label for="">Tuning Name</label>
                <input type="text" id="inpkey" placeholder="Insert Name"> <br>
            </div>
            <form class="" action="index.html" method="post">
                <div class="formBox">
                    <select class="mynoteslist" id="inpvalue">
                        <option value="A1">A1</option>
                        <option value="B1">B1</option>
                        <option value="C1">C1</option>
                        <option value="D1">D1</option>
                        <option value="E1">E1</option>
                        <option value="F1">F1</option>
                        <option value="G1">G1</option>
                    </select>
                </div>
                <div class="formBox">
                    <select class="mynoteslist" id="inpvalue2">
                        <option value="A1">A1</option>
                        <option value="B1">B1</option>
                        <option value="C1">C1</option>
                        <option value="D1">D1</option>
                        <option value="E1">E1</option>
                        <option value="F1">F1</option>
                        <option value="G1">G1</option>
                    </select>
                </div>
            </form>
            <button type="button" id="btninsert">Save Tuning </button>
            <br>
        </fieldset>
        <fieldset>
            <legend>My Tunings</legend>
            <div id="isoutput"> </div>
        </fieldset>
    </div>

Im trying add multiple inpvalues to a key. I cant seem to add another inpvalue as it seems to only accept the first value. Im wondering if theres a simple way around this?

javascript

let inpkey = document.getElementById("inpkey");
let inpvalue=document.getElementById("inpvalue");
//let inpvalue2=document.getElementById("inpvalue2");



let btninsert = document.getElementById("btninsert");
let isoutput = document.getElementById("isoutput");

btninsert.onclick = function(){
  let key = inpkey.value;
  let value = inpvalue.value;
  //let value2 = inpvalue.value;

  console.log(key);
  console.log(value);
//console.log(value2);

  if(key && value) {
    localStorage.setItem(key,value);
    location.reload();
  }
};
for(let i=0; i<localStorage.length; i++){
  let key=localStorage.key(i);
  let value=localStorage.getItem(key);



  isoutput.innerHTML += `${key}: ${value}  <br>` ;
}

the desired output would be something like this Howver if i try to select different options it only takes the first value and applies them to all.

enter image description here


Solution

  • You need to check for the existence of a key and if found, append the new value to the existing value before saving.

    if(key && value) {
    
        // if the key exists
        if(localStorage.getItem(key)){  
    
            // split the existing values into an array
            let vals = localStorage.getItem(key).split(','); 
    
            // if the value has not already been added
            if(! vals.includes(value)){ 
    
                // add the value to the array
                vals.push(value); 
    
                // sort the array
                vals.sort(); 
                
                // join the values into a delimeted string and store it
                localStorage.setItem(key, vals.join(',')); 
            }      
        }else{
            // the key doesn't exist yet, add it and the new value
            localStorage.setItem(key,value);
        }    
        location.reload();
    }
    

    I made a working example of the above code here: https://jsfiddle.net/01rjn3cf/2/

    EDIT: Based on your comments and added example of desired output, I see that you don't want a distinct list of values and that any value can be added to the list of previously selected values. In this case the solution is even easier..

    if(key && value) {
    
        // if the key exists
        if(localStorage.getItem(key)){             
                
            // add this value onto the end of the existing string
            localStorage.setItem(key, localStorage.getItem(key) + ', ' + value); 
                  
        }else{
            // the key doesn't exist yet, add it and the new value
            localStorage.setItem(key,value);
        }    
        location.reload();
    }
    

    EDIT: I modified it as so to work as desired.

    
    
    if(key && value) {
      var content = value + ', ' + value2 + value3;
        // if the key exists
        if(localStorage.getItem(key)){
    
            // add this value onto the end of the existing string
    
            localStorage.setItem(key, content);
    
        }else{
            // the key doesn't exist yet, add it and the new value
            localStorage.setItem(key, content);
        }
        location.reload();
    }
    };
    for(var i=0; i<localStorage.length; i++){
      var key=localStorage.key(i);
      var value=localStorage.getItem(key);
    
    
    
      isoutput.innerHTML += `${key}: ${value}  <br>` ;
    }