I have a form in the +page.svelte
file and I want to do a submission but without a <button />
.
For example I have a <select>
element inside <form>
, now when the user choose the selection, it triggers to submit the value to the +page.server.ts
file
A rough example would be like this:
+page.svelte
<form method="POST" use:enhance>
// I'm using svelte select
<Select
name="select"
bind:justValue={value}
items={items}
/>
</form>
Then, on the server file, it would be like this:
+page.server.ts
import { fail, redirect } from '@sveltejs/kit';
import type { Actions } from './$types';
export const actions: Actions = {
default: async ({ request }) => {
const formData = Object.fromEntries(await request.formData());
const res = await fetch(`${environment.apiUrl}/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
value: formData.select
})
});
const item = await res.json();
if(!res.ok) {
return fail(401, { error: 'error', item });
}
return {
success: true,
item
};
},
};
Idk if this is the best solution, but you can use requestSubmit
Get form reference through
bind:this
and then you can trigger
formElement.requestSubmit()
at any moment. In your case you can do it whenSelect
triggers select event