HTML Forms with JSON

Excerpt

HTML Elements used in HTML forms do not support JSON based dataset out of the box and the FormData class also is quiet incomplete.

Here is a web component that extends form elements to work with JSON data.

Using Browser standard FormData

The browser supports the FormData class that can be used to fetch all data from form elements.

This is implementing the behavior that is known from the classic Form Submit to submit all data using a POST request and the application/form-data or other data formats. This can be converted to a JavaScript Object.

But the JSON object created from the FormData is not strictly following the JSON approach:

Also a reverse operation to modify a form value is not implemented.

These are small gaps in the native browser implementation that can be healed easily by using a WebControl that is attached to the form element. It supports getting and setting the form data using a propper JavaScript object.

Implementation details

When the form is ready it gets analyzed once to retrieve the possible object attributes and to create a default record with the default values.

The attributes that should be treated as booleans are found as they are represented by checkboxes.

The getJsonData() method returns the current values from the form.

The setJsonData(d) method can be used to set a single or multiple form values without directly accessing the HTML elements directly.

Pimp up FORMs to use with JSON data

To enrich <form> elements to work with JSON data the following code is needed:

By using is="form-json" the included class is now extending the form functionality.

The attribute method=dialog stops the standard "submit" behavior.

Example

(hidden)
s

new form functions

Form Data returned:

Raw:



    

Enriched:




    

See Also

Tags

JavaScript