乐闻世界logo
搜索文章和话题

How to not reset the form on submit with ` use : enhance ` in Svelte?

1个答案

1

In Svelte, if you want to reset the form after submission without using custom behaviors like use:action or use:enhanced, you can clear the form fields by directly manipulating DOM elements. Here is a concise example demonstrating how to achieve this.

svelte
<script> let name = ''; let email = ''; function handleSubmit(event) { event.preventDefault(); // Prevents the default form submission behavior // Add code to send data to the server here // Reset form fields after submission name = ''; email = ''; } </script> <form on:submit={handleSubmit}> <label for="name">Name:</label> <input type="text" id="name" bind:value={name}> <label for="email">Email:</label> <input type="email" id="email" bind:value={email}> <button type="submit">Submit</button> </form>

In the above code, the handleSubmit function first prevents the default form submission behavior, then manually resets the variables bound to the input fields to their initial values (in this case, empty strings) after the logic (e.g., sending data to the server). This ensures that the input fields appear cleared after form submission.

The advantage of this method is that it is simple and straightforward, and does not rely on external libraries or advanced Svelte features. However, it requires ensuring that all form fields are correctly reset in the submission function, which can become cumbersome when there are many form fields. In such cases, writing a generic reset function or using a form management library may be more efficient.

2024年8月16日 22:03 回复

你的答案