I’ll list for you some ways to do it.
Using the onchange function()
function carro() {
var carros = document.getElementById("carros");
var result = carros.options[carros.selectedIndex].value;
alert(result)
}
Selecione o veiculo: <select id="carros" onChange="carro()">
<option value="Up">Up! 1.0 </option>
<option value="Argo">Argo 1.0</option>
<option value="Ka" selected>Ka SE Plus 1.0 </option>
<option value="Sandero">Sandero Zen 1.0</option>
<option value="Hb20">HB20 Comfort Plus</option>
</select>
I used your suggestion of the onchange() property. This event occurs whenever the value of the element in question is changed.
It is important to keep in mind that programming requires following some good practices as well. For example, you cars instead of Cars and Car() instead of Car(). You can follow the pattern you want to name variables and functions, but remember that in other contexts a standard for nomenclature may be required. It is also good practice to close html tags.
Using an addeventlistener
window.addEventListener("DOMContentLoaded", function() {
const select = document.getElementById("carros");
alert(select.selectedIndex)
});
Selecione o veiculo:
<select id="carros">
<option value="U">Up! 1.0</option>
<option value="A">Argo 1.0</option>
<option value="K" selected>Ka SE Plus 1.0</option>
<option value="S">Sandero Zen 1.0</option>
<option value="H">HB20 Comfort Plus</option>
</select>
In this example, the script sends an alert to display elements marked as Selected. You can adapt it to have the same function as the first example. It does this by registering an event hold to a target element, i.e., by selecting#cars.
If you want to use a select Multiple
var carros = document.getElementById("carros");
var selecionado = []
for(var i = 0; i < carros.length; i++) {
if(carros[i].getAttribute('selected') !== null) {
selecionado.push(carros[i].value)
}
}
alert(selecionado)
Selecione o veiculo: <select id="carros" multiple>
<option value="U" selected>Up! 1.0 </option>
<option value="A">Argo 1.0</option>
<option value="K" selected>Ka SE Plus 1.0 </option>
<option value="S">Sandero Zen 1.0</option>
<option value="H">HB20 Comfort Plus</option>
</select>
In this example, carros[i].getAttribute('selected') !== null
checks the status of the attribute Selected. If you give a console.log(carros[i].getAttribute('selected'))
will see that the result is either null
or ""
(empty string). With a typeof you notice it returns null (Object) and "" (string).
You can see these links to help you:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange
https://developer.mozilla.org/en-US/docs/Web/API/Element/addEventListener