Skip to content

Instantly share code, notes, and snippets.

@yingray
Last active November 23, 2022 07:05
Show Gist options
  • Save yingray/58ca6280e38ad5e717126e00f28d23d0 to your computer and use it in GitHub Desktop.
Save yingray/58ca6280e38ad5e717126e00f28d23d0 to your computer and use it in GitHub Desktop.
Form submit in Typescript
type TFormSubmitOptions = {
body?: { [key: string]: any };
method?: string;
};
const formSubmit = (endpoint: string, options?: TFormSubmitOptions) => {
const { body = {}, method = 'POST' } = options || {};
const form = document.createElement('form');
form.setAttribute('method', method);
form.setAttribute('action', endpoint);
Object.keys(body).forEach((name) => {
const hiddenField = document.createElement('input');
hiddenField.setAttribute('type', 'hidden');
hiddenField.setAttribute('name', name);
hiddenField.setAttribute('value', body[name]);
form.appendChild(hiddenField);
});
document.body.appendChild(form);
form.submit();
return;
};
formSubmit('/download/file');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment