I am creating a form that I want users to be able to edit. The user will fill the form, save that form, fill the form with the next entry, save that form, etc. A clickable div is created each time the form is saved so that the user can go back and see their inputs to ensure they are correct before final submission of all forms. I've been able to save the form data doing this:
var formArray = $('form#popsetForm').serializeArray();
My question: I would now like to fill the form back with the data in formArray when the user clicks on the div. Is there an easy command that will allow me to just provide the array as input and it will auto-fill the form? The below is not real code but what I'm hoping exists.
$('form#popsetForm').populate(formArray)
I don't know if a solution already exists but something like this should work with serializeArray
.
function restoreForm(form, formArray) {
formArray.forEach(function (pair) {
var selector = `input[name="${ pair.name }"], textarea[name="${ pair.name }"]`
var input = $(form).find(selector)
input.val(pair.value);
})
}
https://jsfiddle.net/aycnx0gd/4/
Or like this for regular ol' formData
function restoreForm(form, formData) {
for (var key of formData.keys()) {
var selector = `input[name="${ key }"], textarea[name="${ key }"]`
var input = $(form).find(selector)
var newVal = formData.get(key)
input.val(newVal);
}
}
https://jsfiddle.net/aycnx0gd/2/
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