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 1.7 KiB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # formxtr
  2. Extract form values through the DOM.
  3. ## Motivation
  4. There are many ways to lay out forms.
  5. ## Installation
  6. The library is not yet out on any package manager. Installing through the URL is the preferred way.
  7. ## Usage
  8. For an example form:
  9. ```html
  10. <!-- ... -->
  11. <form id="form">
  12. <input type="text" name="username" />
  13. <input type="password" name="password" />
  14. <button type="submit" name="type" value="client">Log In As Client</button>
  15. <button type="submit" name="type" value="admin">Log In As Admin</button>
  16. </form>
  17. <!-- ... --->
  18. ```
  19. Use the library as follows (code is in TypeScript, but can work with JavaScript as well):
  20. ```typescript
  21. import getFormValues from '@theoryofnekomata/formxtr';
  22. const form: HTMLFormElement = document.getElementById('form');
  23. // optional, but just in case there are multiple submit buttons in the form,
  24. // individual submitters can be considered
  25. const submitter = form.querySelector('[type="submit"][name="type"][value="client"]');
  26. const values = getFormValues(form, submitter);
  27. const processResult = (result: Record<string, unknown>) => {
  28. throw new Error('Not yet implemented.');
  29. };
  30. // Best use case is with event handlers
  31. form.addEventListener('submit', async e => {
  32. const { target: form, submitter } = e;
  33. e.preventDefault();
  34. const values = getFormValues(form, submitter);
  35. // Get the form values and send as request to some API
  36. const response = await fetch(
  37. 'https://example.com/api/log-in',
  38. {
  39. method: 'POST',
  40. body: JSON.stringify(values),
  41. headers: {
  42. 'Content-Type': 'application/json',
  43. },
  44. },
  45. );
  46. if (response.ok) {
  47. const result = await response.json();
  48. processResult(result);
  49. }
  50. })
  51. ```
  52. ## Tests
  53. The library has been tested on JSDOM through Jest, and the real DOM using Cypress.