From 23e97222f845d3a064bf3d3a31118439b4608d97 Mon Sep 17 00:00:00 2001 From: Claudio Pilotti Date: Thu, 2 May 2024 10:29:27 +0200 Subject: [PATCH] feat: include submitter info. Buttons allow you to overwrite a forms `method` with the `formmethod` attribute. `buildRequest` now incorporates submitter info when determining the submit requests method. --- src/index.ts | 18 +++++++++++++++--- test/test.js | 11 +++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/src/index.ts b/src/index.ts index ec181be..b9be521 100644 --- a/src/index.ts +++ b/src/index.ts @@ -65,6 +65,9 @@ export type RemoteFormHandler = (form: HTMLFormElement, kicker: Kicker, req: Sim // element. type Installable = string | HTMLFormElement +// Any element that submits a
+type HTMLSubmitElement = HTMLButtonElement | HTMLInputElement + let formHandlers: Map type Handler = (form: HTMLFormElement) => void @@ -133,7 +136,16 @@ function handleSubmit(event: Event) { return } - const req = buildRequest(form) + let submitter + + if (event instanceof SubmitEvent) { + submitter = event.submitter as HTMLSubmitElement + } else { + submitter = null + } + + const req = buildRequest(form, submitter) + const [kickerPromise, ultimateResolve, ultimateReject] = makeDeferred() event.preventDefault() @@ -202,9 +214,9 @@ async function processHandlers( return kickerWasCalled } -function buildRequest(form: HTMLFormElement): SimpleRequest { +function buildRequest(form: HTMLFormElement, submitter: HTMLSubmitElement | null): SimpleRequest { const req: SimpleRequest = { - method: form.method || 'GET', + method: submitter?.formMethod || form.method || 'GET', url: form.action, headers: new Headers({'X-Requested-With': 'XMLHttpRequest'}), body: null diff --git a/test/test.js b/test/test.js index 8166db9..40b3692 100644 --- a/test/test.js +++ b/test/test.js @@ -164,4 +164,15 @@ describe('remoteForm', function () { assert.isFalse(handlerCalled) document.removeEventListener('submit', defaultPreventHandler, {capture: true}) }) + + it('overwrites form method with buttons formmethod', function (done) { + remoteForm(htmlForm, async (form, wants, req) => { + assert.equal(req.method.toUpperCase(), 'GET') + done() + }) + + const button = document.querySelector('button[type=submit]') + button.formMethod = 'get' + button.click() + }) })