I'm creating my first watchface which requires a configuration page where two strings can be stored (a title and a message).
I'm not too familiar with all the communication things because there aren't really any full on examples out there but I've tried to get as far as possible with this.
Here is the relevant code to all my spaces
main.c
static void inbox_received_callback(DictionaryIterator *iterator, void *context) {
APP_LOG(APP_LOG_LEVEL_INFO, "Message received!");
// Get the first pair
Tuple *t = dict_read_first(iterator);
//Long lived buffers
static char title_buffer[64];
static char message_buffer[124];
// Process all pairs present
while(t != NULL) {
// Process this pair's key
switch (t->key) {
case TITLE_DATA:
snprintf(title_buffer, sizeof(title_buffer), "%s", t->value->cstring);
text_layer_set_text(title_layer, title_buffer);
APP_LOG(APP_LOG_LEVEL_INFO, "TITLE_DATA received with value %d", (int)t->value->int32);
break;
case MESSAGE_DATA:
snprintf(message_buffer, sizeof(message_buffer), "%s", t->value->cstring);
text_layer_set_text(message_layer, message_buffer);
APP_LOG(APP_LOG_LEVEL_INFO, "MESSAGE_DATA received with value %d", (int)t->value->int32);
break;
}
// Get next pair, if any
t = dict_read_next(iterator);
}
}
pebbleScript.js
var title = localStorage.getItem('title') ? localStorage.getItem('title') : 'Title',
message = localStorage.getItem('message') ? localStorage.getItem('message') : "Message that can be changed in watchface 'Settings'";
Pebble.addEventListener('showConfiguration', function(e) {
console.log("Showing configuration");
// Show config page
Pebble.openURL('https://dl.dropboxusercontent.com/s/kzl44khedt5e22d/config.html?dl=0');
});
Pebble.addEventListener('webviewclosed', function(e) {
var options = JSON.parse(decodeURIComponent(e.response));
title = encodeURIComponent(options.title);
message = encodeURIComponent(options.message);
if(title == 'undefined') {
title = 'Title';
} if (message == 'undefined') {
message = "Message that can be changed in watchface 'Settings'";
}
localStorage.setItem('title', title);
localStorage.setItem('message', message);
console.log("Configuration window returned: ", JSON.stringify(options));
});
Pebble.addEventListener('ready', function(e) {
console.log("PebbleKit JS Ready!");
//Construct a dictionary
var
dict = {
'TITLE_DATA' : title,
'MESSAGE_DATA' : message
};
//Send a string to Pebble
Pebble.sendAppMessage(dict, function(e) {
console.log("Send successful.");
}, function(e) {
console.log("Send failed!");
});
});
config.html
<h3>Title:</h3>
<input type="text" name="title" id="title"></input>
<h3>Message:</h3>
<input type="text" name="message" id="message"></input>
<br>
<input type="submit" id="cancelButton" value="Cancel">
<input type="submit" id="saveButton" value="Save">
<script>
$('#cancelButton').click(function() {
location.href = 'pebblejs://close';
});
$('#saveButton').click(function() {
var options = {
title: $('title').val(),
message: $('#message').val()
}
location.href = 'pebblejs://close#' + encodeURIComponent(JSON.stringify(options));
});
function getURLVariable(name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)",
regex = new RegExp(regexS),
results = regex.exec(window.location.href);
if (results == null) return "";
else return results[1];
}
$(document).ready(function() {
var priorTitle = getURLVariable('title');
priorTitle = decodeURI(priorTitle);
if (priorTitle) {
$('#title').html(priorTitle);
}
var priorMessage = getURLVariable('message');
priorMessage = decodeURI(priorTitle);
if (priorMessage) {
$('#message').html(priorMessage);
}
});
</script>
If anyone can see why this isn't working as intended I'd much appreciate help :) Please let me know if there are any other details I should include.
I'm using CloudPebble for the development. I've done the title and message keys in settings and defined them in my main.c as well so it's not that.
A note that I should make is, in the app log it shows "TITLE_DATA received with value....." but not the "MESSAGE_DATA received...." So the problem may lie somewhere over there.
You're declaring your "long lived buffers" inside the function:
static void inbox_received_callback(DictionaryIterator *iterator, void *context) {
...
//Long lived buffers
static char title_buffer[64];
static char message_buffer[124];
...
}
If you want them to stay in scope (persist), you need to declare them up with the other globals:
static Window *s_main_window;
static char title_buffer[64];
static char message_buffer[124];
Related
I'm a little worried and in a hurry and I'm not sure if this is the right place to ask this, but I literally have no idea where else to ask.
Long story short, I wanted to clear my gmail account from spam and found the following link while searching for a way to do this:
https://www.labnol.org/internet/gmail-unsubscribe/28806/
Like a complete idiot, I followed the instructions blindly without suspecting anything. After completing the steps, nothing really happened (the spreadsheet wasn't filling) so I stopped the script and removed it from my google accounts permissions and started inspecting the code that was used. It consists of three files, the google script:
function getConfig() {
var params = {
label:doProperty_("LABEL") || "Unsubscribe"
};
return params;
}
function config_() {
var html = HtmlService.createHtmlOutputFromFile('config')
.setTitle("Gmail Unsubscriber")
.setWidth(300).setHeight(200).setSandboxMode(HtmlService.SandboxMode.IFRAME);
var ss = SpreadsheetApp.getActive();
ss.show(html);
}
function help_() {
var html = HtmlService.createHtmlOutputFromFile('help')
.setTitle("Google Scripts Support")
.setWidth(350).setHeight(120);
var ss = SpreadsheetApp.getActive();
ss.show(html);
}
function createLabel_(name) {
var label = GmailApp.getUserLabelByName(name);
if (!label) {
label = GmailApp.createLabel(name);
}
return label;
}
function log_(status, subject, view, from, link) {
var ss = SpreadsheetApp.getActive();
ss.getActiveSheet().appendRow([status, subject, view, from, link]);
}
function init_() {
Browser.msgBox("The Unsubscriber was initialized. Please select the Start option from the Gmail menu to activate.");
return;
}
function onOpen() {
var menu = [
{name: "Configure", functionName: "config_"},
null,
{name: "☎ Help & Support",functionName: "help_"},
{name: "✖ Stop (Uninstall)", functionName: "stop_"},
null
];
SpreadsheetApp.getActiveSpreadsheet().addMenu("➪ Gmail Unsubscriber", menu);
}
function stop_(e) {
var triggers = ScriptApp.getProjectTriggers();
for(var i in triggers) {
ScriptApp.deleteTrigger(triggers[i]);
}
if (!e) {
Browser.msgBox("The Gmail Unsubscriber has been disabled. You can restart it anytime later.");
}
}
function doProperty_(key, value) {
var properties = PropertiesService.getUserProperties();
if (value) {
properties.setProperty(key, value);
} else {
return properties.getProperty(key);
}
}
function doGmail() {
try {
var label = doProperty_("LABEL") || "Unsubscribe";
var threads = GmailApp.search("label:" + label);
var gmail = createLabel_(label);
var url, urls, message, raw, body, formula, status;
var hyperlink = '=HYPERLINK("#LINK#", "View")';
var hrefs = new RegExp(/<a[^>]*href=["'](https?:\/\/[^"']+)["'][^>]*>(.*?)<\/a>/gi);
for (var t in threads) {
url = "";
status = "Could not unsubscribe";
message = threads[t].getMessages()[0];
threads[t].removeLabel(gmail);
raw = message.getRawContent();
urls = raw.match(/^list\-unsubscribe:(.|\r\n\s)+<(https?:\/\/[^>]+)>/im);
if (urls) {
url = urls[2];
status = "Unsubscribed via header";
} else {
body = message.getBody().replace(/\s/g, "");
while ( (url === "") && (urls = hrefs.exec(body)) ) {
if (urls[1].match(/unsubscribe|optout|opt\-out|remove/i) || urls[2].match(/unsubscribe|optout|opt\-out|remove/i)) {
url = urls[1];
status = "Unsubscribed via link";
}
}
}
if (url === "") {
urls = raw.match(/^list\-unsubscribe:(.|\r\n\s)+<mailto:([^>]+)>/im);
if (urls) {
url = parseEmail_(urls[2]);
var subject = "Unsubscribe";
GmailApp.sendEmail(url, subject, subject);
status = "Unsubscribed via email";
}
}
if (status.match(/unsubscribed/i)) {
UrlFetchApp.fetch(url, {muteHttpExceptions: true});
}
formula = hyperlink.replace("#LINK", threads[t].getPermalink());
log_( status, message.getSubject(), formula, message.getFrom(), url );
}
} catch (e) {Logger.log(e.toString())}
}
function saveConfig(params) {
try {
doProperty_("LABEL", params.label);
stop_(true);
ScriptApp.newTrigger('doGmail')
.timeBased().everyMinutes(15).create();
return "The Gmail unsubscriber is now active. You can apply the Gmail label " + params.label + " to any email and you'll be unsubscribed in 15 minutes. Please close this window.";
} catch (e) {
return "ERROR: " + e.toString();
}
}
function parseEmail_(email) {
var result = email.trim().split("?");
return result[0];
}
And two other .html files called config.html:
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<script>
function closeWindow() {
google.script.host.close();
}
function showError(error) {
document.getElementById("error").innerHTML = error;
}
function showConfig(params) {
if (params.label !== "")
document.getElementById("label").value = params.label;
return;
}
function validate() {
var label = document.getElementById("label").value;
if (label.trim() === "") {
showError("Please enter a Gmail label name..");
return;
} else {
showError("Saving configuration, please wait..");
var params = {
label: label
};
google.script.run.withSuccessHandler(showError).saveConfig(params);
}
}
</script>
<form>
<div class="form-group block">
<p style="margin-bottom:4px;">Enter Gmail Label Name:</p>
<input type="text" id="label" name="label" placeholder="Your email address.." style="width: 250px;" />
</div>
<p>
<input class="blue" type="button" value="Save configuration" onclick="validate()" />
<input class="green" type="button" value="Close window" onclick="google.script.host.close()" />
</p>
<p class="error" id="error"></p>
</form>
<script>
google.script.run.withSuccessHandler(showConfig).getConfig();
</script>
And lastly help.html:
<head>
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons.css">
<base target="_blank">
</head>
<div class="block">
<p>If you are need help with the program, please refer to the online tutorial. For support and customization, please submit your requirements at <strong>ctrlq.org</strong>.</p>
</div>
<div class="block">
<a class="button blue" href="mailto:amit#labnol.org" style="width:120px;">amit#labnol.org</a>
<a class="button green" href="https://twitter.com/labnol" style="width:120px;margin-right:10px">Tweet #labnol</a>
<input class="red" type="button" value="Close" onclick="google.script.host.close()" />
</div>
Is there any way that my account could be in any danger?
I am the author of this Google Script and it is completely safe. In fact, you have access to the full source code so you know exactly what it is doing.
Also, if you like to remove any Google Script from your account, here's how:
Go to https://security.google.com/settings/security/permissions
Click the script you wish to uninstall
Next click Remove and you are done.
I have /Views/Movies/Index.cshtml with
<input type="button" id="getmoviex" value="Get moviex" />
<ul id="moviex_list"/>
<p>
Title: #Html.TextBox("SearchTitle") <br />
</p>
I have /Controllers/MoviesController.cs with
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult moviex(string SearchGenre, string SearchTitle, string SearchActor)
{
var db = new CinemaContext();
db.Configuration.ProxyCreationEnabled = false;
var Movie = from m in db.Movie
select m;
if (!String.IsNullOrEmpty(SearchTitle))
{
Movie = Movie.Where(s => s.Title.Contains(SearchTitle));
}
return Json(db.Movie.ToList(), JsonRequestBehavior.AllowGet);
}
I have Javascript.js with
$(document).ready(function () {
$('#getmoviex').click(function () {
$.getJSON("/Movies", null, getmoviex);
});
});
Have I correctly written /Movies? Or this should be /Views/Movies?
function getmoviex(moviex) {
$("#moviex_list").text("");
$.each(moviex, function (i) {
$("#moviex_list").append("<li>" + this + "</li>");
});
}
How can I display info or list info from my query? Or view some output with error?
First make sure you button click does not trigger a request to server. Preventing default behavior is a standard way of doing it:
$('#getmoviex').click(function (event) {
$.getJSON("/Movies", null, getmoviex);
event.preventDefault();
});
As for the URL, it should not be to view, but to action instead. Your action is moviex and controller is Movies, so
$.getJSON("/Movies/moviex", null, getmoviex);
The rest looks fine, so that should do it.
you need to pass your arguments as well in url (GET).
Something like this could work:
$('#getmoviex').click(function(event) {
event.preventDefault();
$.getJSON("/Movies/moviex?SearchGenre=yuorgenre&SearchTitle=Cal&SearchActor=youractor", function(moviex) {
var lis;
//please check the console
console.log(moviex);
$.each(moviex, function(b) {
lis += "<li id='" + b.Id + "'>" + b.Title + "</li>");
}); document.getElementById("moviex_list").innerHTML += lis;
});
});
To avoid circular reference in Serializing you may use:
if (String.IsNullOrEmpty(SearchTitle)) {
return View("Error");
}
var db = new CinemaContext();
var Movie = (from m in db.Movie
Where m.Title.Contains(SearchTitle)
select new {
Id = m.MovieID,
Title = m.Title // can add more properties
}).ToList();
return Json(Movie, JsonRequestBehavior.AllowGet);
I have the following javascript code
ws.onopen = function()
{
ws.send("running?");
};
ws.onmessage = function(evt)
{
var phrase = evt.data
console.log(phrase)
if(phrase == "1")
{
console.log(phrase)
document.getElementById("Button1").text="Pause";
document.getElementById("Label1").text="Running";
}
};
//fired when an error occurs during communication with websocket
ws.onerror = function (error)
{
document.getElementById("Label1").innerHTML = "Unknown"
document.getElementById("Button1").disabled = true;
};
function command()
{
var message = document.getElementById("Button1").value;
ws.send(message);
}
That goes along with the following HTML code
<html>
<script src="script_control.js" type="text/javascript">
</script>
<p>Script status: <label id="Label1"></label></p>
<button id="Button1" onclick="command()">Pause</button>
</html>
Each time the value of phrase outputs to console as "1" signifying a text number one. However nothing changes on the page like it is supposed to even though the expression evaluates to try, why might this be happening?
labels and buttons do not have a value attribute, use textContent:
document.getElementById("Button1").textContent="Pause";
document.getElementById("Label1").textContent="Running";
I created this function for next and previous button, in other words there are 2 buttons in my html page and when i click next or previous the pages in the monocle will also move accordingly,
i read that i have to use a custom page flipper for this but they have not provided an example of how to create one.
this is what i've tried and fails:
function fileSelected(event,str) {
var thefile = document.getElementById('file');
var tval = thefile.value;
var ext = tval.split('.').pop();
var files = event.target.files;
var fname = tval.split(/(\\|\/)/g).pop();
if (ext == "epub" || ext == "EPUB"){
function createReader(bookData) {
Monocle.Reader("reader", bookData);
}
new Epub(files[0], createReader);
}else if(ext == "htm" || ext == "htm" || ext == "html" || ext == "HTML"){
var bookData = {
getComponents: function () {
return [
fname
];
},
getContents: function () {
return [
{title: "test", src: fname}
]
},
getComponent: function (componentId) {
return {url:componentId};
},
getMetaData: function(key) {
return {
title: "Test documents",
creator: "Aron Woost"
}[key];
}
}
window.reader = Monocle.Reader('reader', bookData);
}else{
return false;
}
}
function next(){
Monocle.Reader('reader', {}, {}, function (reader) {
reader.moveTo({ direction: 1 });
});
}
when clicking next will give an undefined error in my console.
any idea as how to implement a custom page flipper?
https://github.com/joseph/Monocle/wiki/Page-flippers
I am not that savvy in JS. sorry :(
I think the problem is in this block of variable declaration:
var thefile = document.getElementById('file');
var tval = thefile.value;
var ext = tval.split('.').pop();
var files = event.target.files;
var fname = tval.split(/(\\|\/)/g).pop();
Is there any input field with 'value' property applicable, like <input type="text" id="file"> ?
You sure the filename will certainly have a dot in it, i.e. extension?
Also event.target.files looks suspicious.
If there's nothing wrong, please tell which line the console shows error at. You can double click on the error to have the erroneous line highlighted.
My scenario: I have an application that is 9 pages long for a total of about 125 inputs of varying types and sizes (only input, textarea, radio, and selects). I'd like to use local storage to save the form values. The user can move between the pages (e.g. to review before submitting the application) so I don't want to clear the local storage until they submit the application and if they change from page to page, the form should reload its values from local storage. Once they submit the form, then I'll clear the local storage but until then, the local storage should be retained.
I found this great jquery plugin and a demo page which appears to almost do what I'm looking for - well, with two exceptions:
1) The plugin prompts the user if they want to restore their previously entered info which I'd prefer to not have (I'd rather have the data just be there). My navigational buttons at the bottom of the form are simply "Previous" and "Continue" (on the first page, it is just "Continue" and on the last page they would be "Previous" and "Submit Application").
2) The plugin will prompt the user even if there is no data to load (this would be a non-issue if I can just have it load data if there is any and skip it if there is not). For example, the very first visit to the page will prompt the user to restore previously entered data.
Here is a link to the jquery.remember-state.js used in the demo page.
=======================================================
I took the demo above and tweaked the jquery.remember-state.js to try and make it do what I need but it isn't working correctly.
Here is my (jsFiddle).
NOTE 1: the jsFiddle is meant to just show my code and is not a necessarily a working example in the jsFiddle environment. If you copy the code to your local environment, you should be able to access the console.log to see if/what gets saved to the localStorage.
NOTE 2: S.O. wants formatted code inline so I'll see what I can do to make it format correctly.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>LocalStorage and Unload State Save</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="../jQueryPlugins/RememberState/form.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<!-- use the modified jquery.remember-state.js code in the JavaScript panel instead
the script tag below is the original js file
<script src="http://shaneriley.com/jquery/remember_state/jquery.remember-state.js"></script>-->
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
(function($) {
/* jQuery form remember state plugin
Name: rememberState
Version: 1.3
Description: When called on a form element, localStorage is used to
remember the values that have been input up to the point of either
saving or unloading. (closing window, navigating away, etc.) If
localStorage isn't available, nothing is bound or stored.
The plugin looks for an element with a class of remember_state to show
a note indicating there is stored data that can be repopulated by clicking
on the anchor within the remember_state container. If the element doesn't
exist, it is created and prepended to the form.
Usage: $("form").rememberState("my_object_name");
Notes: To trigger the deletion of a form's localStorage object from
outside the plugin, trigger the reset_state event on the form element
by using $("form").trigger("reset_state");
*/
if (!window.localStorage || !window.JSON) {
if (console && console.log) {
!window.localStorage && console.log("ERROR: you browser does not support" +
" localStorage (use this polyfill https://gist.github.com/350433)");
!window.JSON&& console.log("ERROR: you browser does not support" +
" JSON (use this polyfill http://bestiejs.github.com/json3/)");
}
return $.fn.rememberState = function() { return this; };
}
var remember_state = {
name: "rememberState",
clearOnSubmit: false, //default was true;
// ****************************
/*noticeDialog: (function() {
return $("<p />", {"class": "remember_state"})
.html('Do you want to restore your previously entered info?');
})(),*/
// ****************************
ignore: null,
noticeSelector: ".remember_state",
use_ids: false,
objName: false,
clickNotice: function(e) {
var data = JSON.parse(localStorage.getItem(e.data.instance.objName)),
$f = $(this).closest("form"),
$e;
for (var i in data) {
$e = $f.find("[name=\"" + data[i].name + "\"]");
if ($e.is(":radio, :checkbox")) {
$e.filter("[value=" + data[i].value + "]").prop("checked", true);
}
else if ($e.is("select")) {
$e.find("[value=" + data[i].value + "]").prop("selected", true);
}
else {
$e.val(data[i].value);
}
$e.change();
}
e.data.instance.noticeDialog.remove();
e.preventDefault();
},
chooseStorageProp: function() {
if (this.$el.length > 1) {
if (console && console.warn) {
console.warn("WARNING: Cannot process more than one form with the same" +
" object. Attempting to use form IDs instead.");
}
this.objName = this.$el.attr("id");
}
},
errorNoID: function() {
if (console && console.log) {
console.log("ERROR: No form ID or object name. Add an ID or pass" +
" in an object name");
}
},
saveState: function(e) {
var instance = e.data.instance;
var values = instance.$el.serializeArray();
// jQuery doesn't currently support datetime-local inputs despite a
// comment by dmethvin stating the contrary:
// http://bugs.jquery.com/ticket/5667
// Manually storing input type until jQuery is patched
instance.$el.find("input[type='datetime-local']").each(function() {
var $i = $(this);
values.push({ name: $i.attr("name"), value: $i.val() });
});
values = instance.removeIgnored(values);
values.length && internals.setObject(instance.objName, values);
},
save: function() {
var instance = this;
if (!this.saveState) {
instance = this.data(remember_state.name);
}
instance.saveState({ data: { instance: instance } });
},
removeIgnored: function(values) {
if (!this.ignore) { return values; }
$.each(this.ignore, function(i, name) {
$.each(values, function(j, input) {
if (name === input.name) { delete values[j]; }
});
});
return values;
},
init: function() {
var instance = this;
// ****************************
/* if (instance.noticeDialog.length && instance.noticeDialog.jquery) {
instance.noticeDialog.find("a").bind("click." + instance.name, {
instance: instance
}, instance.clickNotice);
}*/
// ****************************
instance.chooseStorageProp();
if (!instance.objName) {
instance.errorNoID();
return;
}
if (localStorage[instance.objName]) {
// ****************************
/*if (instance.noticeDialog.length && typeof instance.noticeDialog === "object") {
instance.noticeDialog.prependTo(instance.$el);
}
else {
instance.$el.find(instance.noticeSelector).show();
}*/
// ****************************
}
if (instance.clearOnSubmit) {
instance.$el.bind("submit." + instance.name, function() {
instance.$el.trigger("reset_state");
$(window).unbind("unload." + instance.name);
});
}
instance.$el.bind("reset_state." + instance.name, function() {
localStorage.removeItem(instance.objName);
});
// ****************************
/*$(window).bind("unload." + instance.name, { instance: instance }, instance.saveState);
instance.$el.find(":reset").bind("click.remember_state", function() {
$(this).closest("form").trigger("reset_state");
});*/
}
};
var internals = {
setObject: function(key, value) { localStorage[key] = JSON.stringify(value); },
getObject: function(key) { return JSON.parse(localStorage[key]); },
createPlugin: function(plugin) {
$.fn[plugin.name] = function(opts) {
var $els = this,
method = $.isPlainObject(opts) || !opts ? "" : opts;
if (method && plugin[method]) {
plugin[method].apply($els, Array.prototype.slice.call(arguments, 1));
}
else if (!method) {
$els.each(function(i) {
var plugin_instance = $.extend(true, {
$el: $els.eq(i)
}, plugin, opts);
$els.eq(i).data(plugin.name, plugin_instance);
plugin_instance.init();
});
}
else {
$.error('Method ' + method + ' does not exist on jQuery.' + plugin.name);
}
return $els;
};
}
};
internals.createPlugin(remember_state);
})(jQuery);
});//]]>
</script>
<script>
var thisPage = 'page1'; //defines the variable to use for local storage
$(function() {
$("form")
.rememberState({objName: thisPage})
.submit(function() {localStorage.setItem(thisPage, $(this).serializeArray());
return true;
});
});
</script>
</head>
<body>
<form method="post" action="page2.cfm">
<fieldset>
<dl>
<dt><label for="first_name">First Name</label></dt>
<dd><input type="text" name="first_name" id="first_name" /></dd>
<dt><label for="last_name">Last Name</label></dt>
<dd><input type="text" name="last_name" id="last_name" /></dd>
</dl>
</fieldset>
<fieldset class="actions">
<input type="submit" value="Continue" />
</fieldset>
</form>
</body>
</html>
I thought this was going to be tougher than it was. Here is the solution I came up with:
On the form page when the submit button is pressed:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var thisPageID = 'page1'; // each page gets its own
$('form').submit(function() {
var formFields = $(this).serialize();
localStorage.setItem(thisPageID, formFields);
data = localStorage.getItem(thisPageID);
return true;
});
});
</script>
Then on the final page, I retrieve the data for each page by its page id from the local storage and populate my div tags with the data.
function getLocalData(id){
var ApplicantData;
ApplicantData = localStorage.getItem(id);
if (ApplicantData){
$.each(ApplicantData.split('&'), function (index, elem) {
var vals = elem.split('=');
var $div = $("#"+vals[0]);
var separator = '';
// console.log($div);
if ($div.html().length > 0) {
separator = ', ';
}
$div.html($div.html() + separator + decodeURIComponent(vals[1].replace(/\+/g, ' ')));
});
}
}
Some of the Articles that helped me (some SO, some external):
- Clear localStorage
- http://www.simonbingham.me.uk/index.cfm/main/post/uuid/using-html5-local-storage-and-jquery-to-persist-form-data-47
- http://www.thomashardy.me.uk/using-html5-localstorage-on-a-form
There were more but this is all I still had open in tabs.