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, e.g. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With