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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Web Forms In React For Enterprise Platforms
  • How to Get Word Document Form Values Using Java
  • Lightning Data Service for Lightning Web Components

Trending

  • Agile’s Quarter-Century Crisis
  • The Future of Java and AI: Coding in 2025
  • The Role of AI in Identity and Access Management for Organizations
  • Navigating Change Management: A Guide for Engineers

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.7K 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

  • Exploring Intercooler.js: Simplify AJAX With HTML Attributes
  • Dynamic Web Forms In React For Enterprise Platforms
  • How to Get Word Document Form Values Using Java
  • Lightning Data Service for Lightning Web Components

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!