jQuery: Save whole form Data into LocalStorage, and return it back on Refresh.

06 April 2020
jQuery: Save whole form Data into LocalStorage, and return it back on Refresh.

Sometimes we need to keep user input data somewhere, to return it back to it's place on refresh, or even after some time. Usually we need this to make User Experience much better. To achieve that we need to write a small jQuery script. And here it is!

        var formData = {
			set : function (){
				var  formData = []; // Here we are defining the array of elements
				localStorage.removeItem('formData ');
				$('form input[type=text]').each(function(){
//loop through form input fields
					formData .push({ name: this.name, value: this.value});
				});
//here we are converting whole array to json
				localStorage.formData = JSON.stringify(formData);
			},

			get : function (){
				if(localStorage.formData  != undefined){
					formData  = JSON.parse(localStorage.formData);
					for (var i = 0; i < formData.length; i++) {
						$('[name='+formData[i].name+']').val(formData[i].value);
					}
				}
			}
		}
		formData.get(); // method to call form data from FORM, when page loaded
		$("input").change( function() {
			formData.set(); // method to set input data on change
		});

 

That's it, Simple as that!

Thank you!