Why does not this program work in Chrome?

0
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>          
    <fieldset><legend>Escolha</legend>
        <select>
            <optgroup label="Decimal" onclick="f_decimal()">
                <option onclick="carro()">Carro</option>
                <option onclick="moto()">Moto</option>
            </optgroup>     
        </select>   
    </fieldset> 
    <script>
        function carro(){
        alert("Você escolheu carro.")
        }
        function moto(){
        alert("Você escolheu moto.")
        }
    </script>
</html>
    
asked by anonymous 26.04.2018 / 05:19

1 answer

2

The tag option contains the global HTML events and this includes onclick() . For some reason this relationship may or may not work in some browsers. This is because you do not use the onclick() event in the option elements but rather use the onchange() / a> tag in select .

function mudou() {
  
  var valor = document.getElementById("teste").value;
  
  if(valor == "carro") {
    carro();
  }
  else if(valor == "moto") {
    moto();
  }
  
}

function carro(){
  alert("Você escolheu carro.")
}

function moto(){
  alert("Você escolheu moto.")
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Teste</title>
</head>
<body>          
    <fieldset><legend>Escolha</legend>
        <select id="teste" onchange="mudou()">
            <optgroup label="Decimal">
                <option value="carro">Carro</option>
                <option value="moto">Moto</option>
            </optgroup>     
        </select>   
    </fieldset> 
</html>

References:

26.04.2018 / 22:39