Skip to content

Instantly share code, notes, and snippets.

@ozgurg
Created January 26, 2025 18:36
Show Gist options
  • Save ozgurg/4b84fe0130a2b930b926b3bbf823c49b to your computer and use it in GitHub Desktop.
Save ozgurg/4b84fe0130a2b930b926b3bbf823c49b to your computer and use it in GitHub Desktop.
type FormElement = HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement;
export const setFormValuesFromQuery = <T extends Record<string, any>>(
form: HTMLFormElement,
searchParams?: URLSearchParams
): Partial<T> => {
if (searchParams === undefined) {
searchParams = new URLSearchParams(window.location.search);
}
const result = {} as Partial<T>;
for (const _htmlFormControl of form.elements as HTMLFormControlsCollection) {
const formElement = _htmlFormControl as FormElement;
if (!formElement.name) continue;
const queryValue = searchParams.get(formElement.name);
if (queryValue === null) continue;
if (["INPUT", "TEXTAREA"].includes(formElement.tagName)) {
switch (formElement.type) {
case "radio":
case "checkbox":
(formElement as HTMLInputElement).checked = (formElement.value === queryValue);
(result as any)[formElement.name] = (formElement as HTMLInputElement).checked;
break;
case "number":
const numericValue = Number(queryValue);
if (!isNaN(numericValue) && isFinite(numericValue)) {
formElement.value = queryValue;
(result as any)[formElement.name] = numericValue;
}
break;
default:
formElement.value = queryValue;
(result as any)[formElement.name] = queryValue;
}
} else if (formElement.tagName === "SELECT") {
for (const _option of (formElement as HTMLSelectElement).options) {
if (_option.value === queryValue) {
_option.selected = true;
break;
}
}
}
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment