DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Build a Dynamic Web Form Using Camunda BPMN and DMN
  • Automating a Web Form With Playwright MCP and MySQL MCP
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Web Forms In React For Enterprise Platforms

Trending

  • The Middleware Gap in AI Agent Frameworks
  • Building a High-Throughput Distributed Sequence Generator Using the Hi-Lo Algorithm
  • Testing AI-Infused Apps: A Dual-Layer Framework for AI Quality Assurance
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial

How To Handle Forms in Svelte?

Forms are essential to any kind of web application development and in this post, we will learn how to handle them in Svelte by using on:submit directive.

By 
Saurabh Dashora user avatar
Saurabh Dashora
DZone Core CORE ·
Feb. 14, 22 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
2.9K Views

Join the DZone community and get the full member experience.

Join For Free

In this post, we will learn how to handle forms in Svelte.

Forms are an integral part of any web application. They are the primary way in which you collect information from the application user. Forms can enhance the user experience. Also, they can have a significant impact on the overall data quality of your application.

1 – Creating the Form

Let us now put together the form:

 
<main>
    <h1>Welcome to the Fantasy Library</h1>
    <form>
        <label for="book_name"> <strong> Book Name </strong> </label>
        <input id="book_name" name="book_name" type="text" />

        <label for="author_name"> <strong> Author Name </strong> </label>
        <input id="author_name" name="author_name" type="text" />

        <br />
        <button type="submit">Save</button>
    </form>
</main>


This is a very basic form with just two fields. We have the bookName and the author_name. Also, we have a button to submit the form. However, currently, we don’t have any handler for the same.

2 – Form Submit Handler

Let us create the form submit handler:

 
<form on:submit|preventDefault={submitForm}>


We use the on:submit handler. The preventDefault is to prevent the form submission to trigger an HTTP request as per the default form behavior. Basically, we want to trigger the function submitForm.

In the script section of our component, we can also add a placeholder function.

 
<script>
function submitForm() {

}
</script>


3 – Binding the Input Fields

Svelte supports two-way binding using which we can connect the form input fields with the component data fields.

See the updated form HTML:

 
<script>
    let bookName = '';
    let authorName = '';

    let books = [];
    function submitForm() {
        const newBook = {
            id: Math.random().toString(),
            bookName: bookName,
            authorName: authorName
        }
        books = [newBook, ...books]
    }
</script>

<main>
    <h1>Welcome to the Fantasy Library</h1>
    <form on:submit|preventDefault={submitForm}>
        <label for="book_name"> <strong> Book Name </strong> </label>
        <input id="book_name" name="book_name" type="text" bind:value="{bookName}" />

        <label for="author_name"> <strong> Author Name </strong> </label>
        <input id="author_name" name="author_name" type="text" bind:value="{authorName}" />

        <br />
        <button type="submit">Save</button>
    </form>
</main>


As you can see, we use the bind:value directive to bind the input fields to the respective component data field. We also finish the implementation of the submitForm() function. Basically, we generate a new book record and insert the same into the books array.

Please note the use of the below line:

 
books = [newBook, ...books]


We don’t use normal array functions like push() here. This is because these functions do not trigger Svelte’s reactivity. This is explained in the detailed post about correctly updating arrays in Svelte. In a nutshell, we use the assignment operator to update the books array.

4 – Rendering the Books

Finally, we have to show the books that are added using the form.

Below is the updated version of the component:

 
<script>
    import Book from './Book.svelte'
    let bookName = '';
    let authorName = '';

    let books = [];
    function submitForm() {
        const newBook = {
            id: Math.random().toString(),
            bookName: bookName,
            authorName: authorName
        }
        books = [newBook, ...books]
    }
</script>

<main>
    <h1>Welcome to the Fantasy Library</h1>
    <form on:submit|preventDefault={submitForm}>
        <label for="book_name"> <strong> Book Name </strong> </label>
        <input id="book_name" name="book_name" type="text" bind:value="{bookName}" />

        <label for="author_name"> <strong> Author Name </strong> </label>
        <input id="author_name" name="author_name" type="text" bind:value="{authorName}" />

        <br />
        <button type="submit">Save</button>
    </form>
    {#each books as book}
        <Book bookName = {book.bookName}
              authorName = {book.authorName} />
    {/each}
</main>


We use the #each block to render the list of books. You can read more about it in this detailed post on Svelte Each Block.

Below is the code for the Book component:

 
<script>
    export let bookName;
    export let authorName;
</script>
<div>
    <span>Book Name: {bookName} // Author: {authorName}</span>
</div>


It simply receives the bookName and the authorName and displays them.

We can now run the app and if we use the form to add records, we will have them listed properly.

Conclusion

With this, we have successfully learned how to handle forms in Svelte. We used the on:submit listener to trigger a function on form submission and then, update the bound input values as part of the books array.

If you have any comments or queries about the post, please feel free to mention them in the comments section.

Form (document) Svelte

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build a Dynamic Web Form Using Camunda BPMN and DMN
  • Automating a Web Form With Playwright MCP and MySQL MCP
  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Web Forms In React For Enterprise Platforms

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook