Anatole Lucet
Anatole Lucet

Reputation: 1813

Redirect the user after a form submission

I have an <input type="text" /> as a search bar inside a <form>.

Because it's a search bar the user should be redirected to a route similar to : /search?q=thingIWantToSearch when the form is submited.

Currently I'm doing with a location.href but I don't think this is a good way of doing it (or is it?)

Here's my code :

<script>
    let inputValue = '';

    const handleSubmit = () => {
        // there should be some parsing before putting it in the url, but it's not the subject
        location.href = `/search?q=${inputValue}`;
    }
</script>

<form on:submit|preventDefault={handleSubmit}>
    <input type="text" bind:value={inputValue} />
    <button type="submit">submit</button>
</form>

So how can I properly redirect the user on form submission?

Upvotes: 5

Views: 5690

Answers (1)

Steven Bell
Steven Bell

Reputation: 963

If you are using SvelteKit you can use the built-in goto function from $app/navigation. Previously Sappers goto function served the same purpose.

Here's how you can use it:

<script>
  import { goto } from '$app/navigation';

  let inputValue = '';

  const handleSubmit = () => {
    // there should be some parsing before putting it in the url, but it's not the subject
    goto(`/search?q=${inputValue}`);
  };
</script>

<form on:submit|preventDefault="{handleSubmit}">
  <input type="text" bind:value="{inputValue}" />
  <button type="submit">submit</button>
</form>

Upvotes: 10

Related Questions