You can do this using native Javascript. That is, without any external library, and without mixing Javascript in HTML (which is not very advisable).
Then you need to consider three things:
- what to put in HTML
- the event receiver
- where to place Javascript
In HTML the visible part is what is between >
and <
of each option
. What’s in the value
is that it’s important for the programming part. So instead of having the same value
and the text of option
puts in the value
the URL you want. For example:
<option value="/Vilhena.html">Vilhena</option>
To select the element you can use:
var select = document.querySelector('select');
This will work fine if you only have 1 select on the page. If you have more than one you should give a ID to select (the HTML would look like: <select id="meuSelect">
) and you can select it like this:
var select = document.getElementById('meuSelect');
// ou assim:
var select = document.querySelector('#meuSelect');
then attach an event headset for when to change:
select.addEventListener('change', function(){
var valor = this.value;
window.location.href = valor;
});
Finally put the script at the bottom of the page, before the tag </body>
. This way Javascript is read with HTML already loaded in memory.
Did you manage to solve this problem? Did any of the questions help to solve?
– Sergio