Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

123
Visualizações
Linking <option> with onclick

I am building my own shopping website, and I got stuck in this part:

<label for="option">Option</label>
<select id="option">
    <optgroup>
        <option onclick="changeValueA()">Option A</option>
        <option onclick="changeValueB()">Option B</option>
    </optgroup>
</select>

<p>You choosed Option <span id="option-value"></span></p>

<script>
    
    function changeValueA(){
        
       document.getElementById("option-value").innerHTML = "Option A";

    }

    function changeValueB(){
        
       document.getElementById("option-value").innerHTML = "Option B";

    }

</script>

I want to make "option-value" display "Option A" if changeValueA() is called by clicking the Option A from <select>, and I want to make "option-value" display "Option B" if changeValueB() is called by clicking the Option B from <select>.

However, the code doesn't work. It would be really grateful if you help me this part!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

option elements don't respond to click events (as you can see by the added console.logs below); you instead need to check the <select>'s value:

// these functions never run:
function changeValueA() {
  console.log("A") 
  document.getElementById("option-value").innerHTML = "Option A";
}

function changeValueB() {
  console.log("B")
  document.getElementById("option-value").innerHTML = "Option B";
}

// This one will be triggered by the select's onchange handler,
// and passes the selected value in so you don't need multiple 
// similar functions:
function changeValue(val) {
  document.getElementById("option-value").innerHTML = val;
}
<label for="option">Option</label>
<select id="option" onchange="changeValue(this.value)">
  <optgroup>
    <option onclick="changeValueA()">Option A</option>
    <option onclick="changeValueB()">Option B</option>
  </optgroup>
</select>

<p>You chose <span id="option-value"></span></p>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda