jQuery Storage and retrieval form state (with data)

后端 未结 3 901
囚心锁ツ
囚心锁ツ 2021-01-03 09:43

Is there any way to store form state in for example cookie and retrieval it ?
I checked serialize API but I have no idea how to retrieval serialized data on the form.

3条回答
  •  生来不讨喜
    2021-01-03 10:39

    Inspired by Edgar's answer but the copy-paste version.

    var form = $('form');
    if (form.length) {
        var form_data = readCookie('saved_form');
        if (form_data != null) {
            string2form(form, form_data);
        }
    
        form.submit(function() {
            var form_data = form2string(form);
            createCookie('saved_form', form_data, 5);
        });
    }
    
    function createCookie(name, value, days) {
        var expires;
    
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toGMTString();
        } else {
            expires = "";
        }
        document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
    }
    
    function readCookie(name) {
        var nameEQ = encodeURIComponent(name) + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) === ' ')
                c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0)
                return decodeURIComponent(c.substring(nameEQ.length, c.length));
        }
        return null;
    }
    
    
    function form2string($form) {
      return JSON.stringify($form.serializeArray());
    }
    
    function string2form($form, serializedStr) {
      var fields = JSON.parse(serializedStr);
      for(var i = 0; i < fields.length; i++){
        var controlName = fields[i].name;
        var controlValue = fields[i].value;
        if (controlValue != '' && $form.find('[name=' + controlName + ']').val() == ''){
            $form.find('[name=' + controlName + ']').val(controlValue);
        }
      }
    }
    

提交回复
热议问题