Extract and set form values through the DOM—no frameworks required! https://github.com/TheoryOfNekomata/formxtra
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 3.9 KiB

3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # formxtra
  2. _(read "form extra")_
  3. Extract 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 a document,
  7. typically the same document, as soon as the form is submitted. In addition, [applications have limited control over how
  8. the data are formatted on submission](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#dom-fs-enctype)
  9. with this approach. This is why the new way of sending form data is done through AJAX/fetch requests, wherein the data
  10. are serialized into formats like JSON. To turn form data into a specific format requires access to the elements holding
  11. the values to each field in the form.
  12. Some libraries 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()`.
  15. Upon retrieving the field values somehow, some libraries attempt to duplicate the values of the fields as they change,
  16. for instance by attaching event listeners and storing the new values into some internal object or map, which can be
  17. retrieved by some other exposed function.
  18. With `formxtra`, there is no need to traverse the DOM for individual fields to get their values. Provided the fields are
  19. associated to the form (either as a descendant of the `<form>` element or [associated through the `form=""`
  20. attribute](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fae-form)) and has a valid
  21. `name`, the values of these fields can be easily extracted, using the `form.elements` attribute built-in to the DOM and
  22. used for getting its currently associated fields. With this, only the reference to the form is needed. The current state
  23. of the field elements are already stored in the DOM, waiting to be accessed.
  24. ## Installation
  25. The package can be found on:
  26. - [Modal Pack](https://js.pack.modal.sh)
  27. - [npm](https://npmjs.com/package/@theoryofnekomata/formxtra)
  28. - [GitHub Package Registry](https://github.com/TheoryOfNekomata/formxtra/packages/793279)
  29. ## Usage
  30. For an example form:
  31. ```html
  32. <!-- ... -->
  33. <form id="loginForm">
  34. <input type="text" name="username" />
  35. <input type="password" name="password" />
  36. <button type="submit" name="type" value="client">Log In As Client</button>
  37. <button type="submit" name="type" value="admin">Log In As Admin</button>
  38. </form>
  39. <label>
  40. <input type="checkbox" name="remember" form="loginForm" />
  41. Remember my login credentials
  42. </label>
  43. <!-- ... --->
  44. ```
  45. Use the library as follows (code is in TypeScript, but can work with JavaScript as well):
  46. ```typescript
  47. import getFormValues from '@theoryofnekomata/formxtra';
  48. const form: HTMLFormElement = document.getElementById('form');
  49. // optional, but just in case there are multiple submit buttons in the form,
  50. // individual submitters can be considered
  51. const submitter = form.querySelector('[type="submit"][name="type"][value="client"]');
  52. const values = getFormValues(form, { submitter });
  53. const processResult = (result: Record<string, unknown>) => {
  54. throw new Error('Not yet implemented.');
  55. };
  56. // Best use case is with event handlers
  57. form.addEventListener('submit', async e => {
  58. const { target: form, submitter } = e;
  59. e.preventDefault();
  60. const values = getFormValues(form, { submitter });
  61. // Get the form values and send as request to some API
  62. const response = await fetch(
  63. 'https://example.com/api/log-in',
  64. {
  65. method: 'POST',
  66. body: JSON.stringify(values),
  67. headers: {
  68. 'Content-Type': 'application/json',
  69. },
  70. },
  71. );
  72. if (response.ok) {
  73. const result = await response.json();
  74. processResult(result);
  75. }
  76. })
  77. ```
  78. ## Tests
  79. The library has been tested on the static DOM using JSDOM and Jest, and the real dynamic DOM using Cypress.