Dropdown Menu with URL Redirection

Create a dropdown menu using HTML and JavaScript that redirects to a specific URL when an option is selected.

Dropdown Menu with URL Redirection
Photo by Glenn Carstens-Peters / Unsplash

Create a dropdown menu using HTML and JavaScript that redirects to a specific URL when an option is selected.

HTML

<select id="dropdown">
    <option value="">Select an option...</option>
    <option value="https://www.google.com">Google</option>
    <option value="https://www.facebook.com">Facebook</option>
    <option value="https://www.twitter.com">Twitter</option>
</select>

JavaScript

// Get the dropdown element
var dropdown = document.getElementById("dropdown");

// Add event listener to redirect when option is selected
dropdown.addEventListener("change", function() {
  var selectedOption = dropdown.options[dropdown.selectedIndex].value;
  if (selectedOption !== "") {
    window.location.href = selectedOption;
  }
});