JSFiddle - React, Tailwind, and code Playground

by Emil Hemdal

HTML

<form id="test">
    <input id="atitle" name="atitle" type="text" value="" />
    <input id="atitle" name="btitle" type="text" value="" />
</form>
<button onclick="save_values();" type="button">Save Values</button>

JavaScript

function save_values() {
    var current_form = $("#test");
	var formData = current_form.find("input").serialize();
	setCookie("form_data", formData, 730); // Två år
}

function setCookie(key, value, daysUntilExpiration) { // http://stackoverflow.com/questions/9689346/how-to-store-and-reload-a-dynamic-form-via-cookies
	var expiration = new Date();
	expiration.setTime(expiration.getTime()+(daysUntilExpiration*86400000));
	document.cookie = key + "=" + value + ";expires=" + expiration.toGMTString() + ";path=/";
}

function readCookie(name) { // http://www.quirksmode.org/js/cookies.html#link11
	var nameEQ = name + "=";
	var ca = document.cookie.split(";");
	for(var i=0;i<ca.length; i++) {
		var c = ca[i];
		while(c.charAt(0)== " ") {
			c = c.substring(1,c.length);
		}
		if(c.indexOf(nameEQ) == 0) {
			return c.substring(nameEQ.length,c.length);
		}
	}
	return null;
}

function urldecode(url) {
	return decodeURIComponent(url.replace(/\+/g, ' '));
}

var cookie = readCookie("form_data");
if(cookie) {
	var cookie = readCookie("form_data");
	var arr = cookie.split("&");
	var cookie_values = new Array();
	for(var i=0;i<arr.length;i++) {
		var temp = arr[i].split("=");
		cookie_values[temp[0]] = temp[1];
	}
	for(var key in cookie_values) {
		$("[name='"+key+"']").val(urldecode(cookie_values[key]));
	}
	$("#save_information").each(function() {
		if(!$(this).is(":checked")) {
			$(this).parent().click();
		}
	});
} else {
	$("#save_information").each(function() {
		if($(this).is(":checked")) {
			$(this).parent().click();
		}
	});
}