简体   繁体   中英

Populate an HTML Form from a FormData object

Is it possible to store a FormData object of a form and then use that FormData object later to repopulate the stored FormData values back into the form?

For example: HTML

<form id="test_form">
  <input type="text" name="last_name" placeholder="Last Name"/><br/>
  <input type="text" name="first_name" placeholder="First Name"/><br/>
  <input type="date" name="date_of_birth" placeholder="Date of Birth"/><br/>
</form>

Javascript

var f = document.getElementById('test_form');
var data = FormData(f);
...
// mythical function to translate FormData back into form values
f.values(data);

Using this and this , here is how I serialize and deserialize form data:

function formSerialize(form) {
    const data = new FormData(form);
    //https://stackoverflow.com/a/44033425/1869660
    return new URLSearchParams(data).toString();
}

function formDeserialize(form, data) {
    const entries = (new URLSearchParams(data)).entries();
    for(const [key, val] of entries) {
        //http://javascript-coder.com/javascript-form/javascript-form-value.phtml
        const input = form.elements[key];
        switch(input.type) {
            case 'checkbox': input.checked = !!val; break;
            default:         input.value = val;     break;
        }
    }
}

Warning: formDeserialize() won't clear fields that are not included in the stored data, eg empty radio groups or checkboxes. Also, not tested with all <input> types.

Not sure if this is the answer to your question, but if you have JQuery and JQuery View engine, you can use this:

var f = document.getElementById('test_form');
var data = FormData(f);

// Fill the form using JQuery view Engine:
$("#test_form").view(f);

See example on: https://jocapc.github.io/jquery-view-engine/docs/form

You are on the right track with creating the FormData object from the test_form ID.

You can access all the values from the FormData object as so:

var f = document.getElementById('test_form');
var data = new FormData(f);

var lastName = data.get('last_name');
var firstName = data.get('first_name');
var dob = data.get('date_of_birth');

You can also use FormData.getAll to pull all of the data from the object.

var allData = data.getAll;

Hopefully this is what you were asking, if not please let me know and we can get it figured out.

You can store value to variables using FormData but cannot populate back using values. You need to populate for every field individually using script.

You can use localStorage or sessionStorage objects.

Like

localStorage.data = data; //untill clear the browsing history

or

sessionStorage.data = data; //untill session complete

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM