Trigger Onchange in select - javascript

2

Hello, I have a project, and I need to select other items in a select, but it seems very simple, but I was surprised by the difficulty I'm having in doing it. I have tested so far:

Selecione um carro da lista<br>

<select id="mySelect" onchange="myFunction()">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select><br><br>

<div id="modelo" style="display:none;">Escolha um modelo<br><select>
<option value="x1">x1</option>
<option value="x2">x2</option>
<option value="x3">x3</option>
<option value="x4">x4</option>
</select></div>

<script>
function myFunction() {
    var x = document.getElementById("mySelect").value;
if x.value == ("BMW"){
    document.getElementById("modelo").style.display = 'block'; 
}
}
</script>

Basically, it should, when selected the BMW tag, change the display style status of the template div, but it does not work.

    
asked by anonymous 16.11.2015 / 23:31

1 answer

5

You have some very simple errors to solve in your code.

You are assigning the value of select directly to your var x

var x = document.getElementById("mySelect").value;

No if you check if it is BMW, the parentheses are missing

if x.value == ("BMW")

How to solve?

You can correct only in if, as follows

if (x == ("BMW"))

But if you are going to use the element in other places in the future, just assign the element in var x and in if just add the parentheses.

var x = document.getElementById("mySelect");
if (x.value == ("BMW")) {
    document.getElementById("modelo").style.display = 'block';
}

Taking advantage of the @Brunno code, you can add the event directly in the javascript rather than by the on-change of the select.

var select = document.getElementById('mySelect');
select.addEventListener('change', myFunction);
    
17.11.2015 / 00:27