从本地存储中将复选框的值插回到表单

时间:2017-12-01 14:58:11

标签: javascript jquery local-storage

我得到两个复选框1的值总是为false,类型为hidden。我创建了一个本地存储,并在其中存储了复选框的值。我想将值从本地存储放回到我的表单中。有人可以帮助我。



$(document).ready(function() {
  InitalizeCache(GetKey());
});



function GetKey() {
  var key = "local";
  return key;
}

function CacheSpikeData() {
  var form = $("#application-form").serializeArray();
  CacheData(form, GetKey());
}




function InitalizeCache(key) {
  window.onload = function() {
    RecoverFormFromLocalStorage(key);
  }
}



function RecoverFormFromLocalStorage(key) {
  if (localStorage.getItem(key) !== null) {
    var recover = confirm("You have some unsaved changes. Do you want to continue from where you left? ");
    if (recover == true) {
      RecoverFormFromLocalStorage2(key);
      return true;
    } else {
      clearLocalStorage(key);
      return false;
    }
  }
}

function ShowSpikeData() {
  alert(localStorage.getItem(GetKey()));
}

function LoadSpikeData() {
  RecoverFormFromLocalStorage2(GetKey());
}




function clearLocalStorage(key) {
  localStorage.removeItem(key);
}


function CacheData(jsoNform, key) {
  localStorage.setItem(key, JSON.stringify(jsoNform));
}

function RecoverFormFromLocalStorage2(key) {
  var cache = localStorage.getItem(key);
  var record = JSON.parse(localStorage.getItem(key));


  if (cache !== null) {
    $("#application-form *").filter(':input').each(function() {
      if (this.type != "hidden") {

        var cache = localStorage.getItem(key);
        var record = JSON.parse(localStorage.getItem(key));
        var cacheValue = $(record).find("Name=MyStringValue");
        this.value = cacheValue;
        alert(this.name + this.hidden);
      }
    });


  }

}

<html><head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>View - NumberFormattingSample</title>

    
        <link rel="stylesheet" href="/lib/bootstrap/dist/css/bootstrap.css">
        <link rel="stylesheet" href="/css/site.css">
    
    
    
</head>
<body>
  
    <div class="container body-content">
        
<h2>View</h2>

<form id="application-form" action="/Test/EditCheckbox" method="post" novalidate="novalidate">
    <div class="form-horizontal">
        <h4>TestClass</h4>
        <hr>
    <div class="form-group">
        <label class="col-md-2 control-label" for="MyStringValue">MyStringValue</label>      
        <div class="col-md-10">
          
                <input id="MyStringValue" name="MyStringValue" value="" aria-invalid="false" class="valid" type="text">           
          
        </div> 
    </div>
        <div class="form-group">
            <label class="col-md-2 control-label" for="MyValue4">MyValue4</label>      
            <div class="col-md-10">
            <div class="checkbox">
                    <input data-val="true" data-val-required="The MyValue4 field is required." id="MyValue4" name="MyValue4" value="true" type="checkbox">           
            </div>
        </div>
        </div>
        <div class="form-group">
            <label class="col-md-2 control-label" for="MyValue5">MyValue5</label>
            
            <div class="col-md-10">
                <div class="checkbox">
                    <input checked="checked" data-val="true" data-val-required="The MyValue5 field is required." id="MyValue5" name="MyValue5" value="true" type="checkbox">           
                </div>
            </div>
        </div>
        
<select>
    <option>Option</option>
    <option>Option1</option>
  </select>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input value="Cache" type=button class="btn btn-default valid" onclick="CacheSpikeData()" aria-invalid="false">
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input value="Show" type=button class="btn btn-default valid" onclick="ShowSpikeData()" aria-invalid="false">
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input value="Load" type=button class="btn btn-default valid" onclick="LoadSpikeData()" aria-invalid="false">
            </div>
        </div>
  
    </div>
<input name="__RequestVerificationToken" value="CfDJ8PubzbxcXzVMruNKDy4pjvN4hXQ65h4QOkv7uDsWo6fZ2L-XoEq_2ECU5X_vbG2E-06P5vqKof167EUuW9eWazRso-6D-lG8e74rUHikoOhsA_BVeWl4vx3OeutanaJtjbzs8RIpp4WuS74wbuf-5E0" type="hidden"><input name="MyValue4" value="false" type="hidden"><input name="MyValue5" value="false" type="hidden"></form>

<div>
    <a href="/Test">Back to List</a>
</div>


        <hr>
        <footer>
            <p>© 2017 - NumberFormattingSample</p>
        </footer>
    </div>

    
        <script src="/lib/jquery/dist/jquery.js"></script>
        <script src="/lib/bootstrap/dist/js/bootstrap.js"></script>
        <script src="/js/site.js?v=EWaMeWsJBYWmL2g_KkgXZQ5nPe-a3Ichp0LEgzXczKo"></script>
    
    

    

    <script src="/lib/jquery-validation/dist/jquery.validate.js"></script>
    <script src="/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>


    <script src="/js/Caching.js"></script>



</body></html>
&#13;
&#13;
&#13;

我只是尝试将值插回到表单而不删除复选框的隐藏值,而是选取当前值。

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试将InitalizeCache更改为此

function InitalizeCache(key) {
  RecoverFormFromLocalStorage(key);
}

RecoverFormFromLocalStorage2重命名为populateDataFromLocalStorage并更改为此

function populateDataFromLocalStorage(key) {
  var cache = localStorage.getItem(key);

  if (cache !== null) {
    var formJson = JSON.parse(cache);
    $("#application-form *").filter(':input').each(function() {
      var name = $(this).attr('name');

      var formRecord = formJson.find(function(record) {
        return name === record.name;
      }) || {};

      if (this.type === "text") {
        $(this).val(formRecord.value);
      }

      if (this.type === "checkbox") {
        $(this).prop('checked', formRecord.value === 'true');
      }
    });
  }
}

更新LoadSpikeData()以调用正确的函数名称populateDataFromLocalStorage

最后的输入也应该有type="button"