HTML5 localStorage populate form onload - javascript

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.
pageInit is not working though I have jquery mobile installed.
<!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(){
$(window).unload(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">
Input
Output
</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>

1) You could place your page in internet, at best providing QR code to fast load on mobile (free QR generator here), so everyone could easily test
2) Did the browser settings require to grant the domain the rights to store values in local storage? If so, onunload there's no place to accept such request. Place in your ready function one storage instruction to test
3) unload is a bit unreliable (example - browser crash). Have you considered saving values on onblur on inputs? When in large textareas, saving the value in timer, even if user is still editing, is practicised.
4) This question considers also problems with unload function. Maybe future answer to this question will solve your problem?

Related

Focus the first input on load only if no input is focused

I'm trying to set a default focus for all the pages of my site but without changing the focus on page reload.
I mean:
User opens a page.
Focus is automatically set on the 1st input.
User changes focus to the 3rd input.
User refreshes the page.
Focus must not change to the 1st input again. (This is the requirement I fail to accomplish).
My current code is as follows:
$(document).ready(function() {
if($(':focus').length === 0) {
$(':input:not([type="hidden"]):first').focus();
}
});
The condition is true every time!
$(document).ready({
window.onload=function(){
if(session.Storage.getItem("text3")){//if key= text3 is set,then change the focus to 3rd text box.
$('#your3rdTextID').focus();
}
$('#your3rdTextID').focus(function(){
session.Storaage.setItem("text3","selected")//here you set the key as text3 and value as selected for later use.
});
});
You can provide with your own custom conditions.This is just a small example.Hope it helped you.Good luck with your project.
LINK-->HTML5 Local storage vs. Session storage
LINK-->http://www.w3schools.com/html/html5_webstorage.asp
This will work (tested in latest Chrome, IE7 and IE10). Sets a cookie on focus remembering the last focused element, if not, it defaults to the first. It relies on jquery.cookie.js (usage explained in this SO answer). Here is the full HTML+JS source of a minimal working example. Consider changing the cookie name and the input selector (currently 'input'):
<!doctype html>
<html>
<head>
<title>focus test</title>
<meta charset="utf-8" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var $input = $('input'), // get all the inputs
cookieName = 'lastInputFocusIndex', // for consistency
lastIndex = $.cookie(cookieName) || 0; // get the last known index, otherwise default to zero
$input.on('focus',function(){ // when any of the selected inputs are focused
if ( $(this).attr('type') !== 'submit' ) {
$.cookie(cookieName,$input.index(this)); // get their index in the $input list and store it
}
});
$input.eq(lastIndex).focus(); // when the page loads, auto focus on the last known index (or the default of 0)
});
</script>
</head>
<body>
<form method="get" action="">
<p><input type="text" name="first" /></p>
<p><input type="text" name="second" /></p>
<p><input type="text" name="third" /></p>
<p><input type="submit" value="Go" /></p>
</form>
</body>
</html>
Alternatively, you could write your own raw cookies instead of using the cookie helper jQuery plugin; I used it to simplify things.

How can I set a JavaScript variable from a form without a user clicking submit?

I have a form with several different text inputs. The value of each corresponds to a unique JavaScript variable. The variable is then written out on the page.
Is there a way to update the variable automatically so the user doesn't have to hit submit and reload the page each time? I have heard AJAX could be a potential answer to this, but I am unfamiliar with it. If that route is best, are there certain scripts that would be recommended?
You might want to look into jQuery as a good first start into javscript in the browser. For instance, you could write:
<form id="form-id">
<input id="first" type="text" />
<input id="second" type="text" />
<input id="third" type="text" />
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var first, second, third;
$(function(){
$("#form-id").submit(function(){
first = $("#first").value();
second = $("#second").value();
third = $("#third").value();
return false; //Prevent the form from submitting.
});
});
</script>
http://jquery.com/

j-query and javascript form using multiple submits not submitting all data from form

I'm not hugely good with javascript or jQuery, mainly dealing with databases, but I've been having a little trouble getting a rather complex form to submit all its data.
Basically it amounts to three different submit buttons which are meant to post the data in the form with a different privacy setting sent to the table. The table in the database is being updated with the correct privacy setting for each button, but it isn't sending a value for the thought part of the form to the php file it is meant to.
The form is implemented in the HTML as follows:
<FORM action="thought_post.php" method="post" name="thought">
<INPUT onfocus="this.select(); this.value=''"
type="text" value="Thought..."
size="72" />
<div class="megamenu" style="position: absolute; ;left: 478px; top: 11px;">
<ul>
<li class="downservices">Publish...</li>
<div class="servicesdropped">
<ul class="right">
<input type="hidden" name="privacy">
<li>Private</li>
<li>Friends only</li>
<li>Public</li>
</ul>
</div>
</ul>
</div>
</FORM>
and the javascript in the header of the same page is as follows:
<link rel="stylesheet" href="dropdown.css" type="text/css" media="screen" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".downservices").click(function(){
$(".servicesdropped").toggle("fast");
});
});
</script>
<script language="JavaScript" type="text/javascript">
<!--
function poststyle(selectedtype)
{
document.thought.privacy.value = selectedtype ;
document.thought.submit() ;
}
-->
</script>
If anyone could explain why the thought value entered by the user isn't being passed to thought_post.php that would be wonderful!
Try assigning a name to your "thought" input. name is required for a form control to be valid for submission:
<INPUT onfocus="this.select(); this.value=''" type="text" value="Thought..." size="72" name="thought" />
As a side note, make sure your other input is valid markup as well, input tags should be self closing:
<input type="hidden" name="privacy" />
After making these changes and inspecting the form post with FireBug, I could see the correct value for "thought" go through.
Additionally, as the other answer mentions, you should separate your JavaScript and HTML and maybe accomplish this completely with jQuery.
Hope that helps!
Try setting an id for the privacy field (like, say, id="privacy") and selecting it with this:
getElementById("privacy").value = selectedtype;
By the way, you can put all the javascript in one <script> block:
<script type="text/javascript">
$(document).ready(function(){
$(".downservices").click(function(){
$(".servicesdropped").toggle("fast");
});
});
function poststyle(selectedtype)
{
document.thought.privacy.value = selectedtype ;
document.thought.submit() ;
}
</script>
You could also very easily handle the focus event on your input with jQuery so the scripting isn't down in your HTML.

Why aren't my localStorage inputs persistent across pages on my personal computer?

I'm trying out the HTML5 localStorage method for saving data. As I understand it, localStorage should be persistent between pages within the same domain. Please correct me if I'm wrong.
However, for some reason, it appears my localStorage values aren't persisting between pages in the same directory on my computer. Is it not considered the same domain in this case? I'm a little lost.
Here's the code for the two documents in question:
Document 1 (assuming jQuery has been included elsewhere in the document)
<script type="text/javascript">
$(document).ready(function() {
$("form#settings").submit(function(event) {
event.preventDefault();
localStorage["display"] = $("input[name='display']:checked").val();;
localStorage["message"] = $("#disp_message").val();
});
});
</script>
<form id="settings">
<h1>Display</h1>
<input type="radio" name="display" id="message" value="message" />
<label for="message">Replace with message:</label>
<input type="text" id="disp_message" size="60" value="Test content." /><br />
<input type="radio" name="display" id="hide" value="hide" />
<label for="hide">Hide entries</label>
<br />
<br />
<input type="submit" />
</form>
Document 2
<html><body>
<script>
document.write(localStorage["message"]);
document.write("<br />");
document.write(localStorage["message"]);
</script>
</body></html>
Just to clarify the code a touch, the idea is basically to later use this for a Google Chrome extension to hide certain content based on certain criteria. Document 1 would serve as the basis for the Options page, and Document 2 would be the basis for the actual extension script. But that's irrelevant for my question.
As a final clarification, I have tried all three ways of storing and accessing the localStorage variable, i.e.:
localStorage["key"] = "value";
localStorage.key = "value";
localStorage.setItem("key", "value");
Any ideas at all?
If you're testing in Chrome, everything under file://, even folders in the same directory are considered separate domains, so the same origin policy is kicking in, and the localStorage is unique to each.
I don't have a test environment setup at the moment, but launching with the command line flag:
--allow-file-access-from-files should be what you're after.

jQuery : simulating a click on a <input type="file" /> doesn't work in Firefox? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
In JavaScript can I make a “click” event fire programmatically for a file input element?
I've got a web page that looks like this
<html>
<head>
<title>File Upload Click Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div onclick="$('input[type=file]').click()" >CLICK SIMULATOR</div>
<input type="file"></input>
</body>
</html>
My goal is to have the div raise a click event on the file input, and this seems to work exactly as I'd expect in IE and Chrome, but doesn't work in Firefox (no file browser is opened when you click on the div).
Is there a way to get this working in FF?
Is there a way to get this working in FF?
No, and it doesn't work in most common versions of IE, either. IE will open the dialog, but once you've selected a file with it the form won't actually submit.
Abandon hope. The only way to fake a file upload box is using the transparency technique, and that's really not recommended at all as browsers may lay out file upload boxes differently internally (or even provide a file upload control that doesn't include a Browse dialogue), making it highly likely you'll end up with an inoperable form.
Learn to love the grey file upload field, or use progressive enhancement to replace it with Flash where available.
Here's the workaround (FF).
The HTML bit:
<label>Upload Business Logo</label>
<input type="file" name="logo" id="logo" class="file-upload" />
<input type="text" id="text-logo" class="text-upload" readonly/>
<input type="button" id="btn-logo" class="btn-upload" alt="" />
CSS for the input file type:
.file-upload { display:none; }
The jQuery bit:
//bind click
$('#btn-logo').click(function(event) {
$('#logo').click();
});
//capture selected filename
$('#logo').change(function(click) {
$('#text-logo').val(this.value);
});
Upon form submit, the hidden input file will upload the file.
Hope this helps :)

Categories