So I have a piece of code to create a table with some data in it. The first column contains checkboxes, other columns are just regular data.
What I want is that when I click anywhere on a random row (except for header), that entire row's background is turning into yellow (initially white) and the checkbox in that row is ticked. If I click again, everything in the row back to its normal (white row and unticked checkbox).
When I click right at the checkbox, everything acts as expected. However, when I click elsewhere, only the background is changed. I have checked the checked
attribute of the checkbox and it is changed whenever I click (which is like normal). I don't know why this happens. I have looked through many posts with similar issues but it is not helped. I am only a beginner at Javascript and HTML. Please help me with this. Thank you very much!
function changeColorRow(number) {
var elem = document.getElementsByTagName("tr")[number]
var curr_check = document.getElementsByClassName("checkbox").checked
if (!curr_check) {
elem.style.backgroundColor = "yellow"
document.getElementsByClassName("checkbox").checked = true
} else {
elem.style.backgroundColor = "white"
document.getElementsByClassName("checkbox").checked = false
}
}
<h1>List of companies</h1>
<table id="company">
<tr>
<th>Choose</th>
<th>ID</th>
<th>Company</th>
<th>Website</th>
</tr>
<tr onclick="changeColorRow(1)">
<td><input type="checkbox" class="checkbox"></td>
<td>1</td>
<td>ECOPRO Co., Ltd</td>
<td>http://www.ecoprovn.com</td>
</tr>
<tr onclick="changeColorRow(2)">
<td><input type="checkbox" class="checkbox"></td>
<td>2</td>
<td>WAVINA.COM</td>
<td>http://www.wavina.com</td>
</tr>
</table>
Aucun commentaire:
Enregistrer un commentaire