Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

A flexible JavaScript Object and JSON to HTML converter with a focus on forms

NotificationsYou must be signed in to change notification settings

faroncoder/jquery.dform

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

The jQuery.dForm plugin generates HTML markup from JavaScript objects andJSONwith a focus on HTML forms.

Some things you can do:

  • naturally generate JavaScript enhanced markup with your own extensions and custom types
  • use JavaScript and JSON instead of HTML markup since your page doesn't run without JS anyway
  • have an easy way to include jQuery UI elements and other jQuery plugins (some supported out of the box)
  • scaffold forms from business objects of your server side framework

Get started

Download the latest version 1.0.0(~7 Kb minified)

Include it in your jQuery powered page and try this:

<script type="text/javascript">$(function() {  // Generate a form$("#myform").dform({    "action" : "index.html",    "method" : "get",    "html" :    [        {            "type" : "p",            "html" : "You must login"        },        {            "name" : "username",            "id" : "txt-username",            "caption" : "Username",            "type" : "text",            "placeholder" : "E.g. user@example.com"        },        {            "name" : "password",            "caption" : "Password",            "type" : "password"        },        {            "type" : "submit",            "value" : "Login"        }    ]});});</script><form></form>

Or to quickly load an external form definition:

<script type="text/javascript">$(function() {  // Load the form object from path/to/form.json$("#myform").dform('path/to/form.json', function(data) {  this //-> Generated $('#myform')  data //-> data from path/to/form.json});</script><form></form>

Learn more:

Types

Type generators are functions that return a new jQuery DOM object for a specific type. If there is no type generatorfor that type, a basic HTML tag with that name will be created. Every other key in the JavaScript objectyou pass (the dForm object) will be used as an HTML attribute, except if there is asubscriberregistered for that key. A plugin call like this:

$('#my-div').dform({type : "span",id : "the-span"});

Will append an empty<span></span> to the selected element.

Core types

Besides standard HTML tags the following core types are supported:

container{ "type" : "container" }
Creates a<div> container (you can also use{ "type" : "div" })

text{ "type" : "text" }
Creates a text input field

password{ "type" : "password" }
Creates a password input field

submit{ "type" : "submit" }
Creates a submit button input element

reset{ "type" : "reset" }
Creates a reset button input element

hidden{ "type" : "hidden" }
Creates a hidden input element

file{ "type" : "file" }
Create a file upload field

radio{ "type" : "radio" }
Creates a radio button

checkbox{ "type" : "checkbox" }
Creates a checkbox

radiobuttons{ "type" : "radiobuttons" }
Creates a group of radiobuttons (usesoptions subscriber explained below)

checkboxes{ "type" : "checkboxes" }
Creates a group of checkboxes (usesoptions subscriber explained below)

number{ "type" : "number" }
Creates an HTML 5 number input field

url{ "type" : "url" }
Creates an HTML 5 url input field

tel{ "type" : "tel" }
Creates an HTML 5 phone number input field

email{ "type" : "email" }
Creates an HTML 5 email input field

Add your own

You can add your own types by calling$.dform.addType and pass the type name and a functionthat takes the dForm object as a parameter and returns a new jQuery DOM element:

$.dform.addType("hellobutton", function(options) {// Return a new button element that has all options that// don't have a registered subscriber as attributesreturn $("<button>").dform('attr', options).html("Say hello");});

The type generator uses theattrplugin method to add the proper HTML attributes to the button.Now the new type can be used like this:

$('#myform').dform({"type" : "hellobutton","id" : "my-button"});

Which generates:

<button>Say hello</button>

Type generators can be chained. That means, that if you add a type that already existsthis in the generator functionwill refer to the element returned by its previous generator:

$.dform.addType("text", function(options) {return $(this).addClass('my-textfield-class');});$('#myform').dform({type : 'text'});

Now generates

<input type="text" />

Subscribers

While type generators are being used to generate a base element for the given type, subscribers attach tocertain attributes in the dForm object. When traversing the object, all subscribers registered for thatkey will be executed on the current element.

Core subscribers

class{String}
Adds a class to the current element (instead of setting the attribute) using.addClass().

{"type" : "div","class" : "the-div container"}

Generates:

<div></div>

html/elements{String|Array|Object}
Based on the options it either sets the HTML string content of the current element or appends one or an arrayof dForm objects. Theelements subscriber does the same but is kept for backwards compatibility.

{    "type" : "div",    "html" : "Div content"}

Generates:

<div>Div content</div>

This subscriber can also be used to create nested objects by using one or an array of dForm objects:

{"type" : "div","html" :[{"type" : "text"},{"type" : "div","html" : {"type" : "p","html" : "A paragraph"}}]}

Generates:

<div><input type="text" /><div><p>A paragraph</p></div></div>

value{String|Function}
Sets the value of the element using.val()

{"type" : "text","value" : "Text content"}

Generates:

<input type="text" value="Text content" />

css {Object}
Sets CSS properties on an element using.css():

{"type" : "div","css" : {"background-color" : "#FF0000","display" : "none"}}

Generates:

<div></div>

options{Object}
Generates a list of options from a value to text (or dForm Object) mapping for elements of typeselect,radiobuttonsorcheckboxes.

{"type" : "select","options" : {"us" : "USA","ca" : "Canada","de" : {"selected" : "selected","html" : "Germany"}}}

Generates:

<select><option value="us">USA</option><option value="ca">Canada</option><option value="de" selected="selected">Germany</option></select>

To use option groups just pass an object of typeoptgroup:

{"type" : "select","options" : {  "northamerica" : {    "type" : "optgroup",    "label" : "North America",    "options" : {      "us" : "USA",      "ca" : "Canada"    }  },  "europe" : {    "type" : "optgroup",    "label" : "Europe",    "options" : {      "de" : {        "selected" : "selected",        "html" : "Germany"      },      "fr" : "France"    }  }}}

You can also use options oncheckboxes andradiobuttons which will create a list ofcheckboxorradio elements:

{"type" : "checkboxes","options" : {"newsletter" : "Receive the newsletter","terms" : "I read the terms of service","update" : "Keep me up to date on new events"}}

Generates:

<div><input type="checkbox" value="newsletter"><label>Receive the newsletter</label><input type="checkbox" value="terms"><label>I read the terms of service</label><input type="checkbox" value="update"><label>Keep me up to date on new events</label></div>

Note: The Google Chrome JavaScript engine V8 orders object keys that can be cast to numbers by their value andnot by the order of their definition.

caption{String|Object}
Adds a caption to the element. The type used depends on the element type:

  • Alegend onfieldset elements
  • Alabel next toradio orcheckbox elements
  • Alabel before any other element

If the element has its id set, thefor attribute of the label will be set as well.

{"type" : "text","name" : "username","id" : "username","caption" : "Enter your username"}

Generates:

<label for="username">Enter your username</label><input type="text" />

For fieldsets:

{"type" : "fieldset","caption" : "Address"}

Generates:

<fieldset><legend type="ui-dform-legend">Address</label></fieldset>

type{String}
Besides looking up the correct Type Generator it also adds a dform specific class to the element using$.dform.options.prefix (ui-dform- by default) and the type name.

{"type" : "text"}

Generates:

<input type="text" />

Set$.dform.options.prefix = null; if you don't want any classes being added.

Add your own

It is easy to add your own subscribers. Similar to a type generator you just pass the key name you want to subscribeto and a function that takes the options and the type name as a parameter to$.dform.subscribe.this in thesubscriber function will refer to the current element. That way it is possible to add an alert to thehellobutton example created in thetypes section:

$.dform.subscribe("alert", function(options, type) {// Just run if the type is a hellobuttonif(type === "hellobutton") {this.click(function() {alert(options);});}});

And then you can use the plugin like this:

$("#mydiv").dform({"type" : "hellobutton","alert" : "Hello world!"});

Which generates:

<button>Say Hello</button>

And alerts "Hello world!" when the button is clicked. Like type generators, subscribers will also be chained.You can therefore add multiple subscribers with the same name adding behaviour or reacting to different types.

Special subscribers

Currently there are two types of special subscribers:

[pre]{Object}
Functions registered with this name will be called before any processing occurs and get the original options passed.

[post]{Object}
Functions registered with this name will be called after all processing is finished and also get the originaloptions passed.

Plugin

jQuery plugin methods

Thedform plugin function follows the jQuery plugin convention of taking an options object or amethod name as the first parameter to call different methods:

$(form).dform(options [, converter]){Object}{String}
Append the dForm object to each selected element. If the element is of the same type (e.g. if you are appendingatype : 'form' on a<form>) or if no type has been given run the subscribers andadd the attributes on the current element. Optionally use a converter with a given name.

$(form).dform(url [, success]){String}{Function}
Load a JSON form definition using GET from a given URL and execute a success handler when it returns.The handler gets the data passed and hasthis refer to the form element.

$(form).dform('run', options){Object}
Run all subscribers from a given dForm object on the selected element(s).

$(form).dform('run', name, options, type){String}{Mixed}{String}
Run a subscriber with a given name and options on the selected element(s) using a specific type.Usually used internally.

$(form).dform('append', options [, converter]){Object}{String}
Append a dForm element to each selected element. Optionally using a converter with thegiven name.

$(form).dform('attr', options){Object}
Set each attribute from the options object that doesn't have a corresponding subscriber registered.

$(form).dform('ajax', params [, success] [, error]){Object|String}{Function}{Function}
Load a form definition using Ajax. The params take the same options as ajQuery Ajax call.

Static functions

$.keySet(object){Object}
Return an array of the objects keys.

$.withKeys(object, keys){Object}{Array}
Returns a new object that contains all values from the givenobject that have a key which is also in the array keys.

$.withoutKeys(object, keys){Object}{Array}
Returns a new object that contains all value from the givenobject that do not have a key which is also in the array keys.

$.dform.options
Static options for generating a form. Currently only$.dform.options.prefixis being used.

$.dform.defaultType(options){Object}
A type generator that will be used when no other registered type has been found.The standard generator creates an HTML element according to the type given:

{"type" : "a","href" : "http://daffl.github.com/jquery.dform","html" : "Visit the plugin homepage"}

Generates:

<a href="http://daffl.github.com/jquery.dform">Visit the plugin homepage</a>

$.dform.types([name]){String}
Returns all type generators for a given type name. If no name is given, a map of type namesto an array of generator functions will be returned.

$.dform.addType(name, generator [, condition]){String}{Function}{Boolean}
Add a new type with a given name and generator function which takes the options as the parameterand returns a new element. Optionally pass a condition which will add the type only if it is true.

$.dform.subscribe(name, subscriber [, condition]){String}{Function}{Boolean}
Add a new subscriber function for a given name that takes the value and type name as the parameter and will havethis set to the current element. Optionally pass as condition which will add the subscriber only if it is true.

$.dform.subscribers([name])
Returns all subscribers for a given name. If no name is given, an object containing all subscribers willbe returned.

$.dform.hasSubscription(name){String}
Returns if there is at least one subscriber registered with the given name.

$.dform.createElement(options){Object}
Returns a new element either using a registered type generator or the default type generator.

jQuery UI

jQuery.dForm automatically adds support for whichever jQuery UI plugin is available.If the form has theui-widget class the plugin will automatically turn buttons into jQuery UI buttons and addcorners totext,textarea,password andfieldset elements.

Note: jQuery UI has to be loadedbefore the dForm plugin.

Types

Most jQuery UI widgets have an appropriate type generator implemented. Besides normal HTML attributes,each take the same options as described inthe jQuery UI documentation.

progressbar{ "type" : "progressbar" }
Creates a progressbar. Use the options as described in thejQuery UI progressbar documentation.

{"type" : "progressbar","value" : "20"}

slider{ "type" : "slider" }
Creates aslider element.

{"type" : "slider","step" : 5,"value" : 25}

accordion{ "type" : "accordion" }
Creates a container for a jQueryUI accordion. Use theentries subscriber to add elements.You can use anyjQueryUI accordion option in the definition.The caption in each entries element will be used as the accordion heading:

{  "type" : "accordion",  "animated" : "bounceslide",  "entries" : [    {      "caption" : "First entry",      "html" : "Content 1"    },    {      "caption" : "Second entry",      "html" : "Content 2"    }  ]}

tabs{ "type" : "tabs" }
Creates a container for a set of jQuery UI tabs. Use theentries subscriber to add elements.You can use anyjQueryUI tabs option in the definition.The caption in each entries element will be used as the tab heading. You can either pass an arrayof entries and set theid attribute individually or an object which will use the key name as the id:

{  "type" : "accordion",  "entries" : [    {      "caption" : "Tab 1",      "id" : "first",      "html" : "Content 1"    },    {      "caption" : "Tab 2",      "id" : "second",      "html" : "Content 2"    }  ]}

Which is equivalent to:

{  "type" : "accordion",  "entries" : {    "first": {      "caption" : "Tab 1",      "html" : "Content 1"    },    "second" : {      "caption" : "Tab 2",      "html" : "Content 2"    }  ]}

Subscribers

Some other features have been implemented as subscribers:

entries{Object}
Add entries to anaccordion ortabs element. See the accordion and tabs type documentation for examples.

dialog{Object}
Turns the current element into a jQueryUI dialog. Pass thejQueryUI dialog optionsor an empty object for the defaults.

resizable{Object}
Makes the current element resizable. Pass thejQueryUI resizable optionsor an empty object for the defaults.

datepicker{Object}
Adds a datepicker to a text element. Pass thejQueryUI datepicker optionsor an empty object for the defaults:

{  "type" : "text",  "datepicker" : {    "minDate" : "+1"  }}

autocomplete{Object}
Adds autocomplete functionality to a text element. Pass thejQueryUI autocomplete options.

Other plugins

Form validation

jQuery.dForm adds avalidate subscriber if thejQuery Form Validationplugin is available. The options passed are added asvalidation rulesetsto the element:

{"type" : "text","validate" : {"required" : true,"minlength" : 2,"messages" : {"required" : "Required input",}}}

If the form has theui-widget class the jQuery UI CSS error classes will be used to highlight fields.

jQuery Globalize

jQuery.Globalize adds internationalization to JavaScript.If available, thehtml andoptions subscribers will be enabled to use internationalized strings and option lists.For example with Globalize configured like this:

Globalize.culture('de');Globalize.addCultureInfo( "de", {  messages: {    "stuff" : {      "hello" : "Hallo Welt",      "options" : {        "de" : "Deutschland",        "ca" : "Kanada",        "fr" : "Frankreich"      }    }  }});

You can create an internationalized form like this:

{  "type" : "div",  "html" : "stuff.hello"}

Which generates:

<div>Hallo Welt</div>

And an options list like:

{  "type" : "select",  "options" : "stuff.options"}

Generates:

<select>  <option value="de">Deutschland</option>  <option value="ca">Kanada</option>  <option value="fr">Frankreich</option></select>

Changelog

1.0.0

  • Improved documentation using DocumentUp
  • QUnit test suite
  • Major API improvements

0.1.4

  • Merged pull request#30:Wrap 'type' as an array so it doesn't break jQuery 1.7.1's $.inArray() when running in IE8
  • Added first QUnit tests
  • Fixed issue #22 with jQuery UI accordion causing problems with captions
  • Removed placeholder plugin. Use HTML 5 placeholders or the jQueryplaceholder plugin
  • Updated documentation engine to DocumentJS and build system to StealJS
  • Merged pull request#19 and#20,support to set up a validate options for validate() in "form" type
  • Merged pull request#26 to support HTML 5 input types
  • Added simple getting started example

0.1.3

0.1.2

  • AddeddformAttr to add HTML attributes to elements
  • Movedplaceholder into a separate plugin
  • Addedreset button type
  • Added dynamic form definition loading by passing a URL to thebuildForm plugin function
  • Addedajax subscriber using thejQuery form plugin athttp://jquery.malsup.com/form
  • Added thedefaultType method to create any HTML element without having to register a type
  • Improved build process

0.1.1

  • Separated type and subscriber functions
  • Added typesfile,container,hidden,accordion,checkboxes andradiobuttons
  • Added auto class generation based on element type
  • Finished jQuery UIaccordion and unified withtabs usage
  • Switched documentation toNatualdocs athttp://naturaldocs.org
  • Added build.xml for generating documentation and minifying JavaScript

0.1

  • Initial release

License

Copyright (C) 2012David Luecke, [http://daffl.github.com/jquery.dform]

The MIT license:

Permission is hereby granted, free of charge, to any person obtaininga copy of this software and associated documentation files (the"Software"), to deal in the Software without restriction, includingwithout limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and topermit persons to whom the Software is furnished to do so, subject tothe following conditions:

The above copyright notice and this permission notice shall beincluded in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OFMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE ANDNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BELIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTIONOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTIONWITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Build Status

About

A flexible JavaScript Object and JSON to HTML converter with a focus on forms

Resources

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp