How to Handle Form in Svelte: Simple and Correct Approach
bind:value on input elements to keep data in sync and listen to the submit event on the <form> to process data. Prevent the default form submission with event.preventDefault() inside the submit handler to control what happens next.Why This Happens
When you try to handle a form in Svelte without binding input values or preventing the default form submission, the page reloads and your data is lost. This happens because HTML forms by default send a request and reload the page on submit.
<script> let name = ''; function handleSubmit(event) { alert(`Name submitted: ${name}`); } </script> <form on:submit={handleSubmit}> <input type="text" placeholder="Enter name" /> <button type="submit">Submit</button> </form>
The Fix
Bind the input's value to a variable using bind:value so Svelte tracks the input. Also, call event.preventDefault() in the submit handler to stop the page reload and handle the data as you want.
<script> let name = ''; function handleSubmit(event) { event.preventDefault(); alert(`Name submitted: ${name}`); } </script> <form on:submit={handleSubmit}> <input type="text" placeholder="Enter name" bind:value={name} /> <button type="submit">Submit</button> </form>
Prevention
Always use bind:value on form inputs to keep your variables updated with user input. Prevent default form submission in your submit handler to control form behavior. Use descriptive variable names and keep your form logic inside functions for clarity.
Enable Svelte's eslint-plugin-svelte3 and use editor extensions to catch missing bindings or event handlers early.
Related Errors
1. Input value not updating: Happens if you forget bind:value. Fix by adding binding.
2. Form submits and reloads page: Happens if you forget event.preventDefault(). Fix by adding it in submit handler.
Key Takeaways
bind:value to keep input values synced with variables.event.preventDefault() in form submit handlers to stop page reload.