Use FormData to remove empty fields

This commit is contained in:
Pieter Lambrecht 2022-09-29 17:19:57 +02:00
parent af003316e7
commit 47a86744c9
5 changed files with 10 additions and 43 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -13,7 +13,6 @@ import { initSideNav } from './sidenav';
import { initRackElevation } from './racks';
import { initLinks } from './links';
import { initHtmx } from './htmx';
import { cleanGetUrl } from './util';
function initDocument(): void {
for (const init of [
@ -42,7 +41,16 @@ function initWindow(): void {
const documentForms = document.forms
for (var documentForm of documentForms) {
if (documentForm.method.toUpperCase() == 'GET') {
documentForm.addEventListener('submit', cleanGetUrl)
// @ts-ignore: // formdata is not yet supported by TS https://github.com/microsoft/TypeScript/issues/36217
documentForm.addEventListener('formdata', function(event) {
// @ts-ignore: // formdata is not yet supported by TS https://github.com/microsoft/TypeScript/issues/36217
let formData = event.formData;
// @ts-ignore: // formdata is not yet supported by TS https://github.com/microsoft/TypeScript/issues/36217
for (let [name, value] of Array.from(formData.entries())) {
// @ts-ignore: // formdata is not yet supported by TS https://github.com/microsoft/TypeScript/issues/36217
if (value === '') formData.delete(name);
}
});
}
}

View File

@ -477,44 +477,3 @@ export function replaceAll(input: string, pattern: string | RegExp, replacement:
return input.replace(pattern, replacement);
}
/**
* Disable empty FormElements before submitting the form. Purpose is to present a clean URL without empty variables.
*
* @param this HTMLFormElement where the FormElements need to be disabled.
*/
export function cleanGetUrl(this: HTMLFormElement): boolean {
var form_elements = this.elements;
for (var element of form_elements) {
// All FormElements are presented as an 'Element'. In order to use the Form specific field, is has to be remapped to the correct FormElement
switch (element.nodeName.toUpperCase()) {
// The SELECT statement requires a different approach. It depends on the selectedIndex, rather that the value.
// selectIndex is only available in the HTMLSelectElement
case "SELECT":
const selectElement = element as HTMLSelectElement;
if (
selectElement.selectedIndex == null ||
selectElement.selectedIndex == -1 ||
selectElement[selectElement.selectedIndex].getAttribute('value') == ''
) {
element.setAttribute('disabled','');
}
break;
// All other FormElements are mapped to the HTMLInputElement to read out the 'value'
default:
const inputElement = element as HTMLInputElement;
if (
!inputElement.value ||
inputElement.value == null ||
inputElement.value == ''
) {
inputElement.setAttribute('disabled','');
}
}
}
return true;
}