Extract and set form values through the DOM—no frameworks required! https://github.com/TheoryOfNekomata/formxtra
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

README.md 4.8 KiB

3 lat temu
3 lat temu
3 lat temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. # formxtra
  2. ![formxtra logo](./docs/assets/formxtra.svg)
  3. **The companion for Web forms!**
  4. Extract and set form values through the DOM.
  5. ## Installation
  6. The package can be found on:
  7. - [Modal Pack](https://js.pack.modal.sh)
  8. - [npm](https://npmjs.com/package/@theoryofnekomata/formxtra)
  9. - [GitHub Package Registry](https://github.com/TheoryOfNekomata/formxtra/packages/793279)
  10. ## Usage
  11. For an example form:
  12. ```html
  13. <!-- ... -->
  14. <form id="loginForm">
  15. <input type="text" name="username" />
  16. <input type="password" name="password" />
  17. <button type="submit" name="type" value="client">Log In As Client</button>
  18. <button type="submit" name="type" value="admin">Log In As Admin</button>
  19. </form>
  20. <label>
  21. <input type="checkbox" name="remember" form="loginForm" />
  22. Remember my login credentials
  23. </label>
  24. <!-- ... --->
  25. ```
  26. Use the library as follows (code is in TypeScript, but can work with JavaScript as well):
  27. ```typescript
  28. // The default export is same with `getFormValues`, but it is recommended to use the named import for future-proofing!
  29. import { getFormValues, setFormValues } from '@theoryofnekomata/formxtra';
  30. // This is the only query we need. On libraries like React, we can easily get form elements when we attach submit event
  31. // listeners.
  32. const form: HTMLFormElement = document.getElementById('form');
  33. // Optional, but just in case there are multiple submit buttons in the form,
  34. // individual submitters can be considered
  35. const submitter = form.querySelector('[type="submit"][name="type"][value="client"]');
  36. const values = getFormValues(form, { submitter });
  37. const processResult = (result: Record<string, unknown>) => {
  38. setFormValues(form, {
  39. username: 'Username',
  40. password: 'verylongsecret',
  41. });
  42. throw new Error('Not yet implemented.');
  43. };
  44. // Best use case is with event handlers
  45. form.addEventListener('submit', async e => {
  46. const { currentTarget: form, submitter } = e;
  47. e.preventDefault();
  48. const values = getFormValues(form, { submitter });
  49. // Get the form values and send as request to some API
  50. const response = await fetch(
  51. 'https://example.com/api/log-in',
  52. {
  53. method: 'POST',
  54. body: JSON.stringify(values),
  55. headers: {
  56. 'Content-Type': 'application/json',
  57. },
  58. },
  59. );
  60. if (response.ok) {
  61. const result = await response.json();
  62. processResult(result);
  63. }
  64. })
  65. ```
  66. ## Tests
  67. The library has been tested on the static DOM using JSDOM, and the real dynamic DOM using Cypress.
  68. ## Motivation
  69. Forms are used to package related data, typically sent to an external location or processed internally. In the browser,
  70. the default behavior of submitting form data is not always preferred, as this is done through loading or reloading a
  71. document as soon as the form is submitted. In addition, [applications have limited control over how the data are
  72. formatted on submission](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-enctype) with
  73. this approach. This is why the new way of sending form data is done through AJAX/fetch requests, wherein the data are
  74. serialized into formats like JSON. To turn form data into a specific format requires access to the elements holding the
  75. values to each field in the form.
  76. Libraries made for extracting form values query field elements in the DOM, which is inefficient since they need to
  77. traverse the DOM tree in some way, using methods such as `document.getElementsByTagName()` and
  78. `document.querySelector()`. This is the same case with setting each form values for, say, prefilling values to save
  79. time. It might be a simple improvement to the user experience, but the logic behind can be unwieldy as there may be
  80. inconsistencies in setting up each field value depending on the form library being used.
  81. Upon retrieving the field values somehow, some libraries attempt to duplicate the values of the fields as they change,
  82. for instance by attaching event listeners and storing the new values into some internal object or map. This is then
  83. retrieved by some other exposed function or mechanism within that library. This is common with reactive frameworks,
  84. where changes to the document are essential to establish functionality and improved user experience.
  85. ---
  86. With `formxtra`, there is no need to traverse elements for individual fields to get and set their values, provided they are:
  87. * Associated to the form (either as a descendant of the `<form>` element or [associated through the `form=""`
  88. attribute](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form))
  89. * Has a valid `name`
  90. The values of these fields can be easily extracted and set, using the `form.elements` attribute built-in to the DOM.
  91. With this, only the reference to the form is needed. The current state of the field elements is already stored in the
  92. DOM, waiting to be accessed.
  93. Additional documentation can be found on the [`docs` directory](./docs).