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

Submitting Form Data

Sveip for å vise menyen

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.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 7. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 7. Kapittel 3
some-alt