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?
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>