Search code examples
htmlactiononchange

Redirect on select option in select box


At the moment I am using this:

<select ONCHANGE="location = this.options[this.selectedIndex].value;">

it redirect me on the location inside of the option value. But it doesn't work as expected .. mean that if I click on the first option of the select, then onChange action not running. I was thinking about javascript, but I think you'll have some better suggestions guys. So how can I make it work if I click on each option it'll redirect me to the it's value?


Solution

  • Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.

    Here's an example:

    https://jsfiddle.net/bL5sq/

    <select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
      <option value="">Select...</option>
      <option value="https://google.com">Google</option>
      <option value="https://yahoo.com">Yahoo</option>
    </select>