jQuery Storage and retrieval form state (with data)

后端 未结 3 903
囚心锁ツ
囚心锁ツ 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:48

    Yes, you can serialize form values with serialize(). Syntax:

    $("#your_form").serialize()
    

    will return a string you can handle, or save to cookie (you can use the jquery cookie plugin).

    EDIT: The above code will serialize, but will be hard to retrieve.
    You should better use serializeArray(), which returns an array of name value pairs ( like: [{name: "age", value: "23"}, {name: "sex", value: "male"}]). You can see the docs for better explanation.

    With that, we can build a "form to string" function and a "string back to form" function:

    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;
        $form.find('[name=' + controlName + ']').val(controlValue);
      }
    }
    

    Use form2string to serialize it and string2form to set the string back to the form. To store and retrive the serialization, you can use the cookie plugin.

    Hope this helps. Cheers

    PS: JSON methods will work only in modern browsers

提交回复
热议问题