如何在提交前在输入字段中发生relaoad时保持值?

时间:2016-01-28 21:53:42

标签: javascript jquery html angularjs

html:

<form name="shippingForm" class="form-horizontal" role="form">
  <div class="form-group">
    <p class="control-p col-sm-2" for="Address">Address Line1<b class="h4-color">*</b>:</p>
    <div class="col-sm-10">
      <input type="text" name="Address" placeholder="Address Line1" ng-model="shipping.addressLine1" class="input-width" ng-init ="shipping.addressLine1" required /><span class="custom-error" ng-show="shippingForm.Address.$dirty && shippingForm.Address.$error.required">Required.</span>
    </div>
</div>
<div class="form-group">
    <p class="control-p col-sm-2" for="Address2">Address Line2:</p>
    <div class="col-sm-10">
        <input type="text" name="AddressLine" placeholder="Address Line2" ng-model="shipping.addressLine2" class="input-width" />
    </div>
</div>

<button type="submit" class="pull-right btn div-margin-left" ng-disabled ="shippingForm.$invalid "ng-click="saveShipping(shipping)">CONTINUE</button>
</form>

js file:

$scope.saveShipping = function(shippingDetails){     
             var userData = storeLocally.get('userInfo');   
             var addr = "Shipping";

                if (userData.customerId){
                     addShippingInfo(shippingDetails,userData.customerId,addr);
                }
                else {        
                    storeLocally.set('shipInfo', shippingDetails);
                    //$location.path(path);
                }
         };         

         function addShippingInfo(shipAdd, custId, addr){

             appServices.addAddress(shipAdd, custId, addr).then(function (d){
                if (d){
                        storeLocally.set('shipInfo', shippingDetails);
                        //console.log("inside function", shippingDetails);
                        //$location.path(path);
                    }           
                 },
                  function (d) {
                      if (d.status == 500) {
                          window.alert("Oops! some problem here..");
                      };
                 });
         };        

即使在提交之前重新加载页面,我仍希望在字段中保留值。我试过饼干,但似乎不是很好的选择使用它。 请提供一些建议来解决这个问题。

1 个答案:

答案 0 :(得分:2)

您可以使用不使用cookie的localStorage和jQuery的.change(),以便每次表单项更改时,使用localStorage存储其新值,并在页面加载时获取这些值,如果它们存在。

示例HTML

<input type="text" id="name" />

的Javascript

if(localStorage.getItem("name") != null)
    {
    $('#name').val() = localStorage.getItem("name");
    }

$('#name').change(function()
    {
    localStorage.setItem("name", $('#name').val());
    });

然后,在提交表单后,您需要将您使用的所有localStorage个变量重置为null。

希望这有帮助!