Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Impara Submitting Form Data | Forms and Final Project
Introduction to Svelte

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.

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 7. Capitolo 3

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 7. Capitolo 3
some-alt