Extract and set form values through the DOM—no frameworks required! https://github.com/TheoryOfNekomata/formxtra
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

README.md 4.7 KiB

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