Submitting Form Data
Scorri per mostrare il menu
After collecting and validating user input, frontend applications often need to submit form data for further processing. This could include logging in, creating accounts, sending messages, or saving settings.
Svelte makes form submission simple through event handling and reactive state.
Creating a Basic Form
Open App.svelte and add the following code:
<script>
let username = "";
</script>
<form>
<input
bind:value={username}
placeholder="Enter username"
/>
<button type="submit">
Submit
</button>
</form>
The form contains a text input and a submit button.
Handling Form Submission
Add a submit handler:
<script>
let username = "";
function handleSubmit() {
console.log(username);
}
</script>
<form on:submit|preventDefault={handleSubmit}>
<input
bind:value={username}
placeholder="Enter username"
/>
<button type="submit">
Submit
</button>
</form>
When the form is submitted, the handleSubmit function runs and logs the username.
Preventing Page Reloads
By default, forms refresh the page after submission.
The preventDefault event modifier prevents this behavior:
on:submit|preventDefault
This allows frontend applications to handle form data dynamically without reloading the page.
Displaying Submitted Data
You can also update the interface after submission.
<script>
let username = "";
let submittedName = "";
function handleSubmit() {
submittedName = username;
}
</script>
<h2>{submittedName}</h2>
The submitted value now appears inside the interface after the form is submitted.
Grazie per i tuoi commenti!
Chieda ad AI
Chieda ad AI
Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione