How to create a multiple values for a single key using local storage

前端 未结 3 821
梦谈多话
梦谈多话 2021-01-06 02:14

As we all know local storage is a key value pair. Trying to create a multiple values to a single key. But unable to get how to pass the multiple values for a single key.

相关标签:
3条回答
  • 2021-01-06 02:45

    This is not possible with localstorage. However, you can store a JSON string as the value for the key, and with a little post-processing, you can extract your three variables:

    var value = ["aa","bb","cc"]
    localStorage.setItem("testKey", JSON.stringify(value));
    var test = JSON.parse(localStorage.getItem("testKey"));
    alert(test);
    
    0 讨论(0)
  • 2021-01-06 02:50

    A single key can only have a single string value in localStorage. You can have multiple keys with different names, or you can do some encoding of the values. For example, you could put all your values in an Array, then encode it using JSON.stringify() and store the result in localStorage. When you read the data back, you can use JSON.parse() to turn it back into an Array.

    0 讨论(0)
  • 2021-01-06 03:01
            <form>
        <label>Mortgage Amount</label>
        <input type="text" id="amount">
        <label>Interest Rate % </label>
        <input type="text" id="interest">
        <label>Mortgage Period (Years)</label>
        <input type="text" id="period">
        <input type="button" value="Submit" id="btn">
        <input type="button" value="GetLocalStorage" id="localbtn">
    </form>
               <script>
    $(document).ready(function () {
    
        $("#btn").click(function () {
    
            var principal = $("#amount").val();
            var interest = $("#interest").val();
            var years = $("#period").val();
            var item = [];
           item.push(principal,interest,years);
           localStorage.item += JSON.stringify({ "principalAmount": principal, "interestAmount": interest, "Period": years });
    
    
        });
    
    0 讨论(0)
提交回复
热议问题