Using Local Storage in a form (Become an expert)

How many times have you filled out a form, only to find you lost an Internet connection, and have to restart afresh? Irritating, isn't it? No problem, we can easily fix this, using Local Storage. In this recipe, we're going to take a look at how you can use it within a simple demo form.

Getting ready

For this recipe, all we'll need in addition to our text editor is one image. It's to provide some background color, and a copy of it is present in the code that accompanies this book. I would strongly recommend creating a new folder to store your demo within. I will assume you have done this for the purposes of this demo.

How to do it...

Perform the following steps, for using Local Storage in a form:

  1. OK, let's make a start by saving the following code to a new HTML document, as useinforms.html:
    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>HTML5 localStorage Demo</title>
      </head>
      <body>
      </body>
    </html>
  2. We need to use jQuery, some CSS, and a custom script, so we need to include references to all three. We will create the appropriate files later in this recipe:
    <link href="css/useinforms.css"rel="stylesheet" type= "text/css" >
    <script src=http://code.jquery.com/jquery-1.8.3.min.js type="text/javascript"></script>
    <script type="text/javascript" src="js/useinforms.js" type="text/javascript"></script>  
  3. Next we need to add our simple form, so add the following code between the <body> tags:
    <form id="localStorageTest" method="post" action="">
      <label>Name:</label>
      <input type="text" name="name" id="name" 
      class="stored" value="" />
    
      <label>Email:</label>
      <input type="email" name="email" id="email" 
      class="stored" value="" />
    
      <label>Message:</label>
      <textarea name="message" id="message" 
      class="stored"></textarea>
    
      <input type="submit" class="demo-button" value="Submit" />
    </form>
  4. We finally need to add the script that will add the values from each form field into LocalStorage. Go ahead and save the following code to a new file called useinforms.js, within a subfolder called js:
    $(document).ready(function () {
      function init() {
        if (localStorage["name"]) {
          $('#name').val(localStorage["name"]);
        }
        if (localStorage["email"]) {
          $('#email').val(localStorage["email"]);
        }
        if (localStorage["message"]) {
          $('#message').val(localStorage["message"]);
        }
      }
      init();
    });
    $('.stored').keyup(function () {
      localStorage[$(this).attr('name')] = $(this).val();
    });
    $('#localStorageTest').submit(function() {
      localStorage.clear();
    });
  5. It's going to look pretty ugly without some form of styling, so let's go ahead and fix that by adding the following code to a new file called useinforms.css, within a subfolder called css. We begin with resetting some of the base styles:
    html, body, div { border:0; font:inherit; font-size:100%; margin:0; padding:0; vertical-align:baseline; }
    html, body { height: 100%; }
  6. Next comes the background. Set styles for paragraphs and the form. The .clear rule is used to display the fields in alignment:
    body { background: url(../images/noise.png) rgb(241, 241, 241); color: #40382B; font-family: 'Tahoma', sans-serif; font-size: 100%; margin-left: 20px; margin-top: 10px; }
    p {font-size: 1em; margin-bottom: 1.25em; line-height: 1.4em; text-align: left;}
    form { padding: 10px; width: 500px; border: 1px solid black; 	border-radius: 4px; }
    
    .clear {clear: both;}
  7. We also need to provide some styles for the labels and input fields used:
    #localStorageTest label { display: block; }
    #localStorageTest input[type=text], 
    #localStorageTest input[type=email] { display: block; margin-	bottom: 10px; width: 97%; border: 1px solid #C5C5C5; 	margin-bottom: 6px; padding: 5px !important; font-size: 	0.9em; }
    #localStorageTest textarea { border: 1px solid #C5C5C5; display: block; font-size: 0.9em; margin-bottom: 6px; padding: 5px !important; width: 97%; max-width: 97%;}
  8. Finally, we want to make the submit button look a little more attractive:
    .demo-button { padding: 5px 12px; background: #4e1216; color: 	#ddd; -webkit-border-radius: 4px; -moz-border-radius: 4px; 	border-radius: 4px; border: 1px solid #4B1115; text-	decoration: none; cursor: pointer; 
    -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 1px 1px rgba(0, 0, 0, 0.2); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), 0 1px 1px rgba(0, 0, 0, 0.2); }
    
    .demo-button:hover { color: #fff; background: #7F5949; border: 	1px solid #4B1115; text-decoration: none; }
    .demo-button:active { -webkit-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); -moz-box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); box-shadow: inset 0 1px 4px rgba(0, 0, 0, 0.6); background: #4e1216; border: 1px solid #4B1115; }
  9. Alright, if all has gone without any issues, you should see something similar to the following result, when previewing this in a browser:
    How to do it...

How it works...

Although there are a few lines of code involved in this recipe, the concept behind them is very simple. We begin by creating our three-field form to act as our framework.

The real magic happens in the accompanying JavaScript file. We create a function called init, which retrieves the values for name, e-mail, and message from the LocalStorage area of the browser. These details will then be shown when you open your browser. Any subsequent change to the contents of each field is automatically saved into the LocalStorage area, using the .keyup() event handler. Finally, when we submit the form, we clear LocalStorage. After all, once you've submitted your form, it's unlikely you will still want details being shown!

We've had a look at a simple form in this recipe, in which we used Local Storage to help prevent loss of information, should the unthinkable happen and you lose your connection to the Internet. That's good, but I know some of you will likely be users of CMS-based systems, and will want to know if the same principle works there too. The good news is that it does. We'll take a look at how that is done, using WordPress as an example, in the next recipe.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset