Categories
JavaScript Answers

How to Add Links in Select Dropdown Options with JavaScript?

Spread the love

Sometimes, we want to add links in select dropdown options with JavaScript.

In this article, we’ll look at how to add links in select dropdown options with JavaScript.

Add Links in Select Dropdown Options with JavaScript

To add links in select dropdown options with JavaScript, we can add the change listen to the drop down.

And when a option is selected, we redirect to the URL given by the selected option value.

For instance, we write:

<select>
  <option value="">Pick a site</option>
  <option value="https://www.google.com">x</option>
  <option value="https://www.yahoo.com">y</option>
</select>

to add the select drop down.

Then we write:

const select = document.querySelector("select")
select.onchange = () => {
  if (select.selectedIndex !== 0) {
    window.location.href = select.value;
  }
};

We select the select element with document.querySelector.

Then we set the onchange property to a function that checks if selectedIndex isn’t 0.

If it isn’t, then we get the value and set that as the value of window.location.href to redirect to the selected option.

Now when we select a choice with a URL as its value, we should see the redirect happen.

Conclusion

To add links in select dropdown options with JavaScript, we can add the change listen to the drop down.

And when a option is selected, we redirect to the URL given by the selected option value.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *