'Setting value of forms from a cookie on page load, but the value disappears as soon as I click on an input
I am trying to save form data as a cookie and then fill out a form if the user has a matching cookie on page load. It seems to work as intended, but then when I click on any input in the form, it causes the values that were set by javascript to clear.
My JS:
// when the user click on the hs-submit button, serialize the form data and save it in a cookie
$('.hs-submit').click(function(e){
e.preventDefault();
var formID = $(this).attr('data-form');
var form = $(`.form-${formID}`).find('form');
var formData = form.serializeArray();
// convert the form to a string
var data = JSON.stringify(formData);
$.cookie(`hs-form-${formID}`, data, { expires: 7, path: '/' });
});
// when the user loads the page, if they have a cookie for the form, populate the form
if($.cookie('hs-form-1')){
var formData = $.cookie('hs-form-1');
// convert the formData to parsedData
var parsedData = JSON.parse(formData);
var form = $(`.form-1`).find('form');
$.each(parsedData, function(i, field){
form.find(`[name="${field.name}"]`).val(field.value);
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
