Redirect to a link when user selects option in a select
By Flavio Copes
How to redirect to a URL when a user selects an option in an HTML select, by listening to the change event and setting window.location in Alpine or plain JS.
To redirect when a user picks an option in a <select>, listen for the change event, read the selected value, and assign it to window.location. Let me show you how I did it.
I had an HTML <select> input field in a form, and I wanted to redirect to another relative URL when the user picked a specific option.
You don’t have control over the single option, for example you can’t detect an option was selected “on the option”.
You must listen to the change event in the select itself.
But you can’t access option attributes, just the value of the option.
So I ended up doing this:
<select
x-on:change="
if (event.target.value.startsWith('/')) {
window.location = event.target.value
}
"
>
<option value="/login">Login</option>
<option value="/signup">Signup</option>
</select>
I’m using Alpine here as I used that in the app.
The startsWith('/') check acts as a guard. Only options whose value looks like a relative URL trigger the redirect. Any other option behaves like a normal select choice, so you can mix “link options” and regular values in the same element.
In plain JS works in the exact same way, except how you get the target, and you use onchange:
<select
onchange="
if (this.value.startsWith('/')) {
window.location = this.value
}
"
>
<option value="/login">Login</option>
<option value="/signup">Signup</option>
</select>
Of course you can use an event listener too but this works quickly and is “in the element” rather than having to use selectors and ids or classes.
Watch out for the preselected option
There’s a catch with the code above. The first option is selected by default when the page loads. Picking it fires no change event, because nothing changed, so the Login redirect never happens.
The fix is a placeholder option at the top:
<option value="" disabled selected>Go to...</option>
Now every real choice is a change. The empty value fails the startsWith('/') check anyway, so the placeholder itself never redirects.
One more caveat: in some browsers, moving through the options with the arrow keys fires change on every step, redirecting keyboard users before they confirmed their choice. If the select is your main navigation, plain links are the safer pattern. For a secondary shortcut inside a form, like my case, this works fine.