I am in the process of creating a mini-survey and I want the buttons to change color when clicked, but return to normal when another button is selected within the same question. Currently, clicking on a button turns it red while leaving the others clear. However, selecting any other button, whether in the current question or the next, resets all buttons to their original state. As a beginner, I would greatly appreciate a clear explanation.
function updateButtonColor(id) {
var buttons = document.getElementsByClassName('btn');
for (var i = 0; i < buttons.length; ++i) {
var item = buttons[i];
item.style.backgroundColor = (item.id == id) ? "red" : "";
}
}
.btn {
width: 100%;
height: 100%;
}
<div class="background1 ">
<div class="transbox ">
<h3 align="center ">Question 1: Disagreeing with a friend on preferences</h3>
<table border="1 ">
</table>
<table id="table1 ">
</table>
<table align="center ">
<tbody>
<tr>
<td><input type="button " value="Not at all likely " button id="tab1 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Slightly likely " button id="tab2 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Somewhat likely " button id="tab3 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Moderately Unlikely " button id="tab4 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Likely " button id="tab5 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Very likely " button id="tab6 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Extremely Likely " button id="tab7 " class="btn " onClick="updateButtonColor(this.id) "></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="background2 ">
<div class="transbox ">
<h3 align="center ">Question 2: Betting a day's income on horse racing.</h3>
<table border="1 ">
</table>
<table align="center ">
<tbody>
<tr>
<td><input type="button " value="Not at all likely " button id="tab8 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Slightly likely " button id="tab9 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Somewhat likely " button id="tab10 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Moderately Unlikely " button id="tab11 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Likely " button id="tab12 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Very likely " button id="tab13 " class="btn " onClick="updateButtonColor(this.id) "></td>
<td><input type="button " value="Extremely Likely " button id="tab14 " class="btn " onClick="updateButtonColor(this.id) "></td>
</tr>
</tbody>
</table>
</div>
</div>