JavaScript

How to change a URL choosing an option of a select of a select input

November 2, 2021

How to change a URL choosing an option of a select of a select input

In this article we will learn how to change a URL choosing an option of a select, ie, by selecting the option the browser will change the URL

change a URL choosing an option of a select cover

Hey you programmer, okay? Let’s learn something new!

To solve the problem of switching pages using the select option, running the approach I’ve chosen, I’m going to use some JavaScript

So we’ll have our basic HTML and CSS structure (if you wish), and then we’ll activate the onChange event using JavaScript

In this event we will create some logic to change the page, so let’s go!

How to make a select input change the URL: practice

Let’s build a basic HTML to start solving our problem, let’s see it:

<!DOCTYPE html>
<html>
 <head>
  <title>Como fazer um select mudar de URL</title>
 </head>
 <body>
  <h1>Mudar de página com Select</h1>
  <select>
   <option>Selecione uma opção</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>
 </body>
</html>

Running this code, the result in the web browser should be like:

Note that the value attribute of the options has already been purposely defined with the links that we are going to access

This will help us on the JavaScript part, to know which URL is the one you want.

So let’s go to JavaScript:

let selectEl = document.getElementsByTagName('select');

selectEl[0].addEventListener('change', function() {
 location.href=this.value;
});

The script is pretty simple, in the first line we define a variable with the select element, so we can have the onChange event reference

After that we create an event listener with addEventListener, which will watch the options change in our select case

On the option change, we take the option value and change the URL for this value

And our goal is reached! 

Conclusion

To solve the problem of: how to make a select change its URL, we use a very practical approach

Running JavaScript code, we insert the select into a variable, and then we monitor the onChange event and when it happens we change the URL

And that’s it for today, see you on the next post! 

Want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x