Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

re-populate form, after saving form data to serialized array Javascript

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)
like image 262
dahlia Avatar asked Oct 29 '22 17:10

dahlia


1 Answers

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/

like image 51
Fred Sladkey Avatar answered Nov 09 '22 23:11

Fred Sladkey