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!
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>