1

I have a requirement where i have to save Form data on iPad, This HTML file will have basic information and form for data collection.

I have to design one page template for iPad, with Photo Gallery, Video Gallery and some text related to project.. More like a presentation. This much is possible and we can keep all the file on iPad and user can access then even if they are not connected to internet.

Issue i am facing is that client want to store form related information in offline (Without internet) mode and only way for me to do it is to use local store.

Since i am new to this i would like to know how i can read this data back from the local store and if it is possible to export this to txt file.

http://codepen.io/anon/pen/gPNMYm

var localStorageAPI = {

    // This method may not be needed as we go along
    // the support is becoming better and better day-by-day
    // http://caniuse.com/#feat=namevalue-storage

    // better to be safe than sorry or get script errors :|
    isSupported: function() {
        return window.localStorage;
    },

    setItem: function(key, value) {
        return localStorage.setItem(key, value);
    },

    getItem: function(key) {
        return localStorage.getItem(key);
    },

    // If do not want to build a wrapper like how I did here but implement 
    // setObject() and getObject(), you can create prototype methods on  
    // Storage

    // Storing Objects in HTML5 localStorage : http://stackoverflow.com/a/3146971/1015046 

    setObject: function(key, object) {
        return localStorage.setItem(key, JSON.stringify(object));
    },

    getObject: function(key) {
        return JSON.parse(localStorage.getItem(key));
    },

    removeItem: function(key) {
        return localStorage.removeItem(key);
    },

    clearAll: function() {
        return localStorage.clear();
    }

};

$(document).ready(function() {

    // Check localStorage support
    if (localStorageAPI.isSupported()) {
        var key = 'longForm';

        // on blur of any form field, save the form data to local storage
        $('.form-control').on('blur', function() {
            // this can be cleaned up better to save 
            // only the relevant form data
            // I am saving the entire form data for simplicity

            // convert Form data to Object
            // http://stackoverflow.com/a/17784656/1015046
            var formObj = {};
            $('form').serializeArray().map(function(x) {
                formObj[x.name] = x.value;
            });

            localStorageAPI.setObject(key, formObj);

        });

        // populate existing form data
        var fData = localStorageAPI.getObject(key);
        if (fData) {
            $.each(fData, function(formEle, formEleVal) {
                $('[name=' + formEle + ']').val(formEleVal);
            });
        }

        // delete the local storage key if the form is "successfully submit"
        $('form').submit(function(e) {
            e.preventDefault();

            // AJAX Call to server..

            // Success

            localStorageAPI.removeItem(key);
        });

    } else {
        alert('No Local Storage Support!');
    }

});

I came across this example. http://thejackalofjavascript.com/getting-started-with-client-side-storage/

Besides this localstored is domain based will it work if we open file as html page on ipad ..

I am sure this is not recommended way of doing thing due to 5BM limitation.

Can we somehow store form data on java-script file.

Learning
  • 19,469
  • 39
  • 180
  • 373
  • _"i would like to know how i can read this data back from the local store and if it is possible to export this to txt file."_ Yes, data can be saved to a local `.txt` file. Is requirement for user to save `formObj` locally ? – guest271314 Feb 21 '16 at 06:48
  • @guest271314, I have a requirement where user will use tablet to show HTML based presentation and ask user to give there feedback. They need to collect data in this manner as they wont have internet connectivity in remote area. – Learning Feb 21 '16 at 11:46
  • See post; utilized `onchange`, `onsubmit` , `onreset` events ; `data URI` to save `.txt` or `.json` file representing `form` data locally – guest271314 Feb 21 '16 at 18:01

1 Answers1

2

I have a requirement where user will use tablet to show HTML based presentation and ask user to give there feedback. They need to collect data in this manner as they wont have internet connectivity in remote area.

You can create an array to store data. At onchange event to set properties , values of an object; push object to array. At onsubmit event of form, prevent default action, use JSON.stringify() , encodeURIComponent() on array; use a element with download attribute set to save results of form locally.

var data = [],
  a = document.getElementsByTagName("a")[0];

document.forms["presentation"].onchange = function(event) {
  var val = {};
  val["name"] = event.srcElement.name;
  val["value"] = event.srcElement.value;
  data.push(val);
  event.srcElement.setAttribute("disabled", true);
}

document.forms["presentation"].onsubmit = function(event) {
  event.preventDefault();
  var formData = JSON.stringify(data, null, 2);
  a.download = "formData-" + new Date().getTime();
  // create a text file
  a.href = "data:text/plain," + encodeURIComponent(formData);
  // save `formData` locally as file with timestamp appended to file name
  a.click();
}

document.forms["presentation"].onreset = function(event) {
  var elems = this.querySelectorAll("input, select");
  for (var i = 0; i < elems.length; i++) {
    elems[i].removeAttribute("disabled")
  }
  // empty `data` array
  data.length = 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form name="presentation">
  <fieldset>
    <select name="color" required>
      <option value="" disabled>select a color</option>
      <option value="green">green</option>
      <option value="gold">gold</option>
      <option value="purple">purple</option>
      <option value="gray">gray</option>
    </select>
    colorful presentation
    <input name="survey" type="radio" value="colorful presentation" />opaque presentation
    <input name="survey" type="radio" value="opaque presentation" />
    <br>
    <label>please leave a brief comment about the presentation
    <input type="text" name="comment" maxlength="20" minlength="5" required placeholder="5-25 charcters, e.g.; 'colorful'" /></label><br />
    <input type="submit" />
    <input type="reset" />
  </fieldset>
</form>
<a></a>
guest271314
  • 1
  • 15
  • 104
  • 177
  • This seems to create file each time user fills the form. and how can i retrieve this information from file for all users who submitted there information. – Learning Feb 22 '16 at 04:37
  • 1
    @Learning Yes, each `js` at post creates a file for each form submission. Can create a single folder to save all files ; could use `input type="file"` to load folder and concatenate files into a single array of array of objects containing properties, values; as the files have a `JSON` structure though saved as `.txt` file following requirement described at Question _"if it is possible to export this to txt file"_ – guest271314 Feb 22 '16 at 04:41