Skip to content

Redirect to a link when user selects option in a select

New Course Coming Soon:

Get Really Good at Git

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.

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.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my HTML Handbook
→ Read my HTML Tutorial on The Valley of Code
→ Read my Alpine.js Tutorial on The Valley of Code

Here is how can I help you: