Reputation: 319
I am struggling with the following.
I have a table with users and when someone clicks on a row, a div should show up right under the line which is clicked and display the information. First I am building up the table:
<table id="table" class="table">
<thead>
//......
</thead>
<tbody>
<?php $i = 1; foreach ($fetchStudenten as $student){ ?>
<tr id="student">
<td><?php echo $i ?></td>
<td><?php echo $user['student_name'] ?></td>
<td><?php echo $user['student_email'] ?></td>
<td><?php echo $user['student_id'] ?></td>
</tr>
<?php if($i == 1){?><tr id="info" colspan="4" style="display: none" class="alert alert-info"><td colspan="4">Display here more info</td></tr><?php } ?>
<?php $i++; } ?>
</tbody>
</table>
As you can see I enter values for each user in the table. I've tried some (pure!) JS scripts, but I didn't get it to work. Is there any option to perform this in only js, not jQuery?
Upvotes: 1
Views: 490
Reputation:
An alternative to Jonas' solution that uses more modern syntax could look like this:
for(const s of document.querySelectorAll(".students")) {
s.addEventListener("click", clickHandler);
}
function clickHandler() {
this.nextElementSibling.style.display = "block";
}
Changes made are:
querySelectorAll
to fetch elements matching the .students
selector.for-of
loop to iterate the students.const
since there's no intention of modifying that variable.addEventListener()
to bind then handler..nextElementSibling
to get the row after the one clicked.Upvotes: 1
Reputation: 138417
"student" should be a class (ids are unique), than you can do:
var students=document.getElementsByClassName("students");
for(var id=0;id<students.length;id++){
students[id].onclick=function(){
this.parentNode.rows[ this.rowIndex + 1 ].style.display="block";
};
}
Upvotes: 1