HTML Forms with JSON
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:
- HTML Input elements with an empty value do not create an attribute
- Checkboxes create an attribute with value "on" when selected - not a boolean value.
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:
- In the header the script must be included like:
<script src="formJsonData.js"></script>
- The form element needs 2 additional attributes:
<form is="form-json" method="dialog">
By using is="form-json" the included class is now extending the form functionality.
The attribute method=dialog stops the standard "submit" behavior.