I am following the example in the O'Reilly "Building iPhone Apps with HTML, CSS and Javascript," I want the values entered from a form to populate after the app closes and reloads, similar to a php 'sticky form.'
The only aspects I changed from the example is that saveSettings is called on submit, and here I have it called on unload (previously on input blur).
Load settings is called on document ready rather than submit.
EDIT I deleted the extra hash sign, i showed code with jquery included (it was included before) I bound saveSettings to unload. The values are still not sticky. When I close the window and open it again they are gone
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.min.js"></script>
<script>
$(document).ready(function(){
$('#current-age').blur(saveSettings);
loadSettings();
});
function loadSettings() {
$('#monthly-income').val(localStorage.income);
$('#saving-per-month').val(localStorage.saving);
$('#current-age').val(localStorage.age);
}
function saveSettings() {
localStorage.age = $('#current-age').val();
localStorage.saving = $('#saving-per-month').val();
localStorage.income = $('##monthly-income').val();
}
</script>
</head>
<body>
<div data-role="content">
<div data-type="horizontal" data-role="controlgroup">
<a href="#foo" data-role="button">Input</a>
<a href="#foo1" id="output-button" data-role="button">Output</a>
</div>
<input type="number" min="500" max="10000" step="100" name="monthly-income" id="monthly-income" value=""/>
<input type="number" min="500" max="10000" step="100" name="saving-per-month" id="saving-per-month" value=""/>
<input type="number" min="16" max="75" step="1" name="current-age" id="current-age" value=""/>
</body>
</html>
To get your code work, you have to apply two changes:
<script src="http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.css"></script>
localStorage.income = $('##monthly-income').val();
tolocalStorage.income = $('#monthly-income').val();
(=omit one sharp, #
).Fiddle: http://jsfiddle.net/fE7pC/
Note: Instead of binding an event listener to blur
, I recommend to bind it to onload
, so that the settings are automatically saved when leaving the page:
$(window).unload(saveSettings);
Another note: jQuery mobile recommends pageInit
, rather than $().ready
. See: http://jquerymobile.com/test/docs/api/events.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With