TheoryOfNekomata 4c69db6c02 | 1 ano atrás | |
---|---|---|
cypress | 1 ano atrás | |
docs | 1 ano atrás | |
src | 1 ano atrás | |
.eslintrc | 1 ano atrás | |
.gitignore | 1 ano atrás | |
.npmignore | 1 ano atrás | |
.prettierrc | 3 anos atrás | |
LICENSE | 1 ano atrás | |
README.md | 1 ano atrás | |
cypress.json | 1 ano atrás | |
package.json | 1 ano atrás | |
pridepack.json | 1 ano atrás | |
publish.sh | 3 anos atrás | |
test-globals.js | 1 ano atrás | |
tsconfig.eslint.json | 1 ano atrás | |
tsconfig.json | 1 ano atrás | |
vitest.config.js | 1 ano atrás | |
yarn.lock | 1 ano atrás |
The companion for Web forms!
Extract and set form values through the DOM.
The package can be found on:
For an example form:
<button id="autofill" type="button">
Autofill login form
</button>
<form id="loginForm">
<input type="text" name="username" />
<input type="password" name="password" />
<button type="submit" name="type" value="client">
Log In As Client
</button>
<button type="submit" name="type" value="admin">
Log In As Admin
</button>
</form>
<label>
<input type="checkbox" name="remember" form="loginForm" />
Remember my login credentials
</label>
Use the library as follows (code is in TypeScript, but can work with JavaScript as well):
import { getFormValues, setFormValues } from '@theoryofnekomata/formxtra';
// This is the only query we need. On libraries like React, we can easily get form elements when we
// attach submit event listeners.
const form: HTMLFormElement = document.getElementById('form');
const processResponse = async (response: Response) => {
const result = await response.json();
alert(`Welcome ${result.user}!`);
};
// Best use case is with event handlers
form.addEventListener('submit', async e => {
const {
currentTarget: thisForm,
submitter,
} = e;
e.preventDefault();
const values = getFormValues(thisForm, { submitter });
// Get the form values and send as request to some API
const response = await fetch(
'https://example.com/api/log-in',
{
method: 'POST',
body: JSON.stringify(values),
headers: {
'Content-Type': 'application/json',
},
},
);
if (response.ok) {
processResponse(response);
}
});
const autofillButton = document.getElementById('autofill');
autofillButton.addEventListener('click', e => {
setFormValues(form, { username: 'admin', remember: true });
});
The library has been tested on the static DOM using JSDOM, and the real dynamic DOM using Cypress.