Code Monkey home page Code Monkey logo

form-saver's Introduction

Form Saver Build Status

A handy little script that lets users save and reuse form data.

Download Form Saver / View the demo


Want to learn how to write your own vanilla JS plugins? Check out "The Vanilla JS Guidebook" and level-up as a web developer. ๐Ÿš€


Getting Started

Compiled and production-ready code can be found in the dist directory. The src directory contains development code.

1. Include Form Saver on your site.

<link rel="stylesheet" href="dist/css/form-saver.css">
<script src="dist/js/form-saver.js"></script>

2. Add the markup to your HTML.

<form id="form-id">
	<div>
		<label>Text Input</label>
		<input name="input" type="text">
	</div>

	<div>
		<label>Text Input to Ignore</label>
		<input data-form-no-save name="input-ignore" type="text">
	</div>

	<div>
		<label>
			<input type="checkbox" name="checkbox1" value="1">
			Checkbox 1
		</label>
	</div>

	<div>
		<label>
		<input type="checkbox" name="checkbox2" value="2">
			Checkbox 2
		</label>
	</div>

	<div>
		<label>
		<input type="radio" name="radioset" value="radio1">
			Radio 1
		</label>
	</div>

	<div>
		<label>
		<input type="radio" name="radioset" value="radio2">
			Radio 2
		</label>
	</div>

	<div>
		<select name="select">
			<option>Select 1</option>
			<option>Select 2</option>
			<option>Select 3</option>
		</select>
	</div>

	<div>
		<textarea name="textarea"></textarea>
	</div>

	<div class="form-saver">
		<div data-form-status></div>
		<div>
			<button data-form-save="#form-id">
				Save Form Data
			</button>
			<button data-form-delete="#form-id">
				Delete Form Data
			</button>
		</div>
	</div>
</form>

Create your forms as normal. All forms must have an ID, all form fields must have a name attribute, and checkboxes and radio buttons must also have a value attribute, or they won't work properly with Form Saver. Use the [data-form-no-save] data attribute to omit a form field from being saved.

You can use a elements instead of buttons to save and delete data:

<a data-form-save="#form-id" href="#">
	Save Form Data
</a>
<a data-form-delete="#form-id" href="#">
	Delete Form Data
</a>

3. Initialize Form Saver.

<script>
	formSaver.init();
</script>

In the footer of your page, after the content, initialize Form Saver. And that's it, you're done. Nice work!

Installing with Package Managers

You can install Form Saver with your favorite package manager.

  • NPM: npm install cferdinandi/form-saver
  • Bower: bower install https://github.com/cferdinandi/form-saver.git
  • Component: component install cferdinandi/form-saver

Working with the Source Files

If you would prefer, you can work with the development code in the src directory using the included Gulp build system. This compiles, lints, and minifies code.

Dependencies

Make sure these are installed first.

Quick Start

  1. In bash/terminal/command line, cd into your project directory.
  2. Run npm install to install required files.
  3. When it's done installing, run one of the task runners to get going:
    • gulp manually compiles files.
    • gulp watch automatically compiles files when changes are made and applies changes using LiveReload.

Options and Settings

Form Saver includes smart defaults and works right out of the box. But if you want to customize things, it also has a robust API that provides multiple ways for you to adjust the default options and settings.

Global Settings

You can pass options and callbacks into Form Saver through the init() function:

formSaver.init({
	selectorStatus: '[data-form-status]', // Selector for the status container (must be a valid CSS selector)
	selectorSave: '[data-form-save]', // Selector for the save button (must be a valid CSS selector)
	selectorDelete: '[data-form-delete]', // Selector for the delete button (must be a valid CSS selector)
	selectorIgnore: '[data-form-no-save]', // Selector for fields to ignore (must be a valid CSS selector)
	deleteClear: true, // Boolean. Reload the page after deleting form data.
	saveMessage: 'Saved!', // Message to display when form data is successfully saved.
	deleteMessage: 'Deleted!', // Message to display when form data is successfully deleted.
	saveClass: '', // Class to add to save success message <div>
	deleteClass: '', // Class to add to delete success message <div>
	initClass: 'js-form-saver', // Class added to `<html>` element when initiated
	callbackSave: function ( btn, form ) {}, // Function to run after a form is saved
	callbackDelete: function ( btn, form ) {}, // Function to run after a form is deleted
	callbackLoad: function ( form ) {} // Function to run after form data is loaded from storage
});

Note: If you change the selectorSave or selectorDelete, you still need to include the [data-form-save] and [data-form-delete] attributes in order to pass in the selector for the form.

Override settings with data attributes

Form Saver lets you override global settings on a form-by-form basis using the [data-options] data attribute:

<button
	data-form-save
	data-options='{
					"saveMessage": "Saved!",
					"saveClass": "alert-success"
	              }'
>
	Save Form Data
</button>

<button
	data-form-delete
	data-options='{
					"deleteMessage": "Deleted!",
					"deleteClass": "alert-success",
					"deleteClear": true
	              }'
>
	Delete Form Data
</button>

Note: You must use valid JSON in order for the data-options overrides to work.

Use Form Saver events in your own scripts

You can also call Form Saver events in your own scripts.

saveForm()

Save a form's data.

formSaver.saveForm(
	btn, // Node that saves the form. ex. document.querySelector('#save-btn')
	formID, // ID of the form to save. ex. #form-id
	options, // Classes and callbacks. Same options as those passed into the init() function.
	event // Optional, if a DOM event was triggered.
);

Example

var options = { saveMessage: 'Your data has been saved. Booya!' };
formSaver.saveForm( null, '#form', options );

deleteForm()

Delete a form's data.

formSaver.deleteForm = function (
	btn, // Node that deletes the form. ex. document.querySelector('#delete-btn')
	formID, // ID of the form to save. ex. #form-id
	options, // Classes and callbacks. Same options as those passed into the init() function.
	event // Optional, if a DOM event was triggered.
);

Example

var btn = document.querySelector('[data-form-delete]');
var formID = btn.form.id;
formSaver.deleteForm( btn, formID );

loadForm()

Load a form's saved data.

formSaver.loadForm = function (
	form, // Form node to delete. ex. document.querySelector('#form')
	options // Classes and callbacks. Same options as those passed into the init() function.
);

Example

var forms = document.forms;
for (var i = forms.length; i--;) {
	var form = forms[i];
	formSaver.loadForm( form );
}

destroy()

Destroy the current formSaver.init(). This is called automatically during the init function to remove any existing initializations.

formSaver.destroy();

Browser Compatibility

Form Saver works in all modern browsers, and IE 10 and above. You can extend browser support back to IE 9 with the classList.js polyfill.

Form Saver is built with modern JavaScript APIs, and uses progressive enhancement. If the JavaScript file fails to load, or if your site is viewed on older and less capable browsers, save and delete data buttons will not be displayed.

How to Contribute

In lieu of a formal style guide, take care to maintain the existing coding style. Don't forget to update the version number, the changelog (in the readme.md file), and when applicable, the documentation.

License

The code is available under the MIT License.

form-saver's People

Contributors

cferdinandi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

form-saver's Issues

Just a lil thanks!

Thank you for this great little plugin!!

Couple of days ago I was to lazy to code a little form saver for a project. Just stumbled across your great plugin, installed and ready!

Luckily you implemented the api for custom stuff :)

Thanks a lot!

Add optimize js

package.json

"gulp-optimize-js": "^1.0.2",

gulpfile.js

var optimizejs = require('gulp-optimize-js');

    var jsTasks = lazypipe()
        .pipe(header, banner.full, { package : package })
        .pipe(optimizejs)
        .pipe(gulp.dest, paths.scripts.output)
        .pipe(rename, { suffix: '.min' })
        .pipe(uglify)
        .pipe(optimizejs)
        .pipe(header, banner.min, { package : package })
        .pipe(gulp.dest, paths.scripts.output);

Add auto-save option

  1. Save automatically when user types.
  2. Provide a hook to delete automatically when they submit the form.

Select value change does not trigger change event

When using the loadForm function programmatically and one of the fields is a select element, the value is effectively updated, but the change event is not triggered, which can cause problems.

In my case, I use Select2 to enhance select boxes, and it seems to rely on the change event to update accordingly to the newly selected value.

It would be nice if something like that could be added:

<selectElement>.dispatchEvent(new Event("change"));

after the select value has been updated.

If you have concerns about it, I would like to know them, otherwise it would be a good addition IMO :)

Unticked checkboxes state not saved

Here is a scenario that has an unexpected result because unticked checkboxes are not saved:

  1. Checkbox is already ticked on page load.
  2. User unticks the box.
  3. User saves data to localStorage.
  4. Page is re-loaded, the checkbox is once again already ticked on page re-load.
  5. User loads data from localStorage. The checkbox remains ticked when it should be unticked.

This would be common when editing a record from a database.

saveForm and deleteForm throw an error when no button defined.

When saveForm or deleteForm are called without a button as their first argument getDataOptions throws an error. An empty object {} is used as a default value instead of its string counterpart "{}".
Json.parse in getDataOptions waits for a string.

Update NPM deps and switch to lib-sass

package.json

"gulp": "^3.9.0",
"node-fs": "^0.1.7",
"del": "^1.2.0",
"lazypipe": "^0.2.4",
"gulp-plumber": "^1.0.1",
"gulp-flatten": "^0.0.4",
"gulp-tap": "^0.1.3",
"gulp-rename": "^1.2.2",
"gulp-header": "^1.2.2",
"gulp-footer": "^1.0.5",
"gulp-watch": "^4.2.4",
"gulp-livereload": "^3.8.0",
"gulp-jshint": "^1.11.1",
"jshint-stylish": "^2.0.1",
"gulp-concat": "^2.6.0",
"gulp-uglify": "^1.2.0",
"karma": "^0.12.37",
"gulp-karma": "^0.0.4",
"karma-coverage": "^0.4.2",
"jasmine": "^2.3.1",
"karma-jasmine": "^0.3.6",
"karma-phantomjs-launcher": "^0.2.0",
"karma-spec-reporter": "^0.0.19",
"karma-htmlfile-reporter": "^0.2.1",
"gulp-sass": "^2.0.3",
"gulp-minify-css": "^1.2.0",
"gulp-autoprefixer": "^2.3.1",
"gulp-svgmin": "^1.1.2",
"gulp-svgstore": "^5.0.2",
"gulp-markdown": "^1.0.0",
"gulp-file-include": "^0.11.1"

gulpfile.js

.pipe(sass({
    outputStyle: 'expanded',
    sourceComments: true
}))

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.