Onchange trigger in select - javascript

Asked

Viewed 6,222 times

3

Hello, I have a project, and I need that, when selecting a particular item in a select, appear (or not) other items, seems to me very simple, but I was surprised by the difficulty I’m having in doing so, here’s what 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 brand BMW, change the display style status of the div model, but it does not work.

1 answer

6


There are some very simple mistakes 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 where you check if it is BMW, are missing parentheses

if x.value == ("BMW")

How to solve?

You can fix only in if, as follows

if (x === 'BMW')

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

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

Taking advantage of @Brunno’s code, you can add the event directly in javascript instead of on-change select.

var select = document.getElementById('mySelect');
select.addEventListener('change', myFunction);
  • 1

    +1 and Follows a jsfiddle to complement =]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.