Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Submitting Form Data | Forms and Final Project
Introduction to Svelte

Submitting Form Data

Свайпніть щоб показати меню

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.

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 7. Розділ 3

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 7. Розділ 3
some-alt