Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!