Retaining form variable values between page navigations

From Code Trash
Jump to: navigation, search

Here are two functions using which you can save form variables in cookies before leaving to another page and when come back the same page the saved cookie data will be restored in those form variables.

For example if you are filling out a long form and meanwhile you left the page to another page for some other process. Now you come back to the form page. What happens normally is all the data in the form will be cleared because the page is loading fresh. in this case these functions will restore the values you had already typed before leaving that page.

So it is like auto fill when you leave a page and come back.

function store_form_values(coname,id)
{
	id = id.split(',');
	var str={};
 
	for(var i=0;i<id.length;i++)
	{
//		if(!document.getElementById(id[i]))alert(id[i])
		if(document.getElementById(id[i]).type=='checkbox')
			str[id[i]] = document.getElementById(id[i]).checked
		else
			str[id[i]] = document.getElementById(id[i]).value
	}
	var fin = JSON.stringify(str)
	setCookie(coname,fin)
 
}
 
function restore_form_values(cook)
{
	var so = getCookie(cook)
	if(!so)return;
	so = JSON.parse(so);
 
	for(i in so)
	{
//		console.log(i);
		switch(document.getElementById(i).type)
		{
			case 'checkbox':
				document.getElementById(i).checked = so[i]
				break;
			case 'text':
			case 'textarea':
				document.getElementById(i).value = so[i]
				break;
			case 'select-one':
				setjsSelectedText(i,so[i]);
				break;
		}
	}
}

The setjsSelectedText function.

function setjsSelectedText(ref,id)
{
	var os = document.getElementById(ref)
	for(var i=0;i<os.options.length;i++)
		if(os.options[i].value==id)os.options.selectedIndex = i;
}

...