-
Notifications
You must be signed in to change notification settings - Fork 6
/
form-association.ts
55 lines (44 loc) 路 2.09 KB
/
form-association.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
const types = ['checkbox', 'textarea', 'input'];
export type HiddenInputType = typeof types;
function getFormByIdOrClosest(element: HTMLElement): HTMLFormElement | null {
const formId = element.getAttribute('form');
const formElement = formId ? document.getElementById(formId) : element.closest('form');
return formElement instanceof HTMLFormElement ? formElement : null;
}
function addHiddenInput(hostingForm: HTMLElement, { name, value }: { name: string, value: string }, hiddenType: HiddenInputType[number]) {
const hiddenInput = document.createElement(hiddenType) as HTMLInputElement;
hiddenInput.style.display = 'none';
hiddenInput.setAttribute('name', name);
hiddenInput.defaultValue = value;
hostingForm.appendChild(hiddenInput);
return hiddenInput;
}
function setValueAndValidity(inputField: HTMLInputElement | undefined, value: string, validationMessage = '') {
if (!inputField) {
return;
}
inputField.value = value;
inputField.setCustomValidity(validationMessage);
}
export function addInputToForm(inputElement: any, hiddenType: HiddenInputType[number] = 'input'): void {
const hostingForm = getFormByIdOrClosest(inputElement);
if (!hostingForm || !inputElement) {
return;
}
inputElement.hiddenInput = addHiddenInput(hostingForm, inputElement, hiddenType);
setValueAndValidity(inputElement.hiddenInput, inputElement.value, inputElement.formElement.validationMessage);
hostingForm.addEventListener('reset', () => {
inputElement.value = inputElement.formElement.value = inputElement.hiddenInput?.defaultValue ?? '';
setValueAndValidity(inputElement.hiddenInput, inputElement.value, inputElement.formElement.validationMessage);
});
inputElement.hiddenInput.addEventListener('invalid', (event: Event) => {
event.stopPropagation();
event.preventDefault();
});
inputElement.addEventListener('change', () => {
setValueAndValidity(inputElement.hiddenInput, inputElement.value, inputElement.formElement.validationMessage);
});
inputElement.addEventListener('input', () => {
setValueAndValidity(inputElement.hiddenInput, inputElement.value, inputElement.formElement.validationMessage);
});
}