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

Submitting Form Data

Veeg om het menu te tonen

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.

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 7. Hoofdstuk 3

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 7. Hoofdstuk 3
some-alt