Infiltrator
Infiltrator

Reputation: 319

Display table row for each user if onclick

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

Answers (2)

user1106925
user1106925

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:

  • Used querySelectorAll to fetch elements matching the .students selector.
  • Used the new for-of loop to iterate the students.
  • Made each student a const since there's no intention of modifying that variable.
  • Declared the handler function outside the loop so that it can be reused.
  • Used addEventListener() to bind then handler.
  • Used .nextElementSibling to get the row after the one clicked.

Upvotes: 1

Jonas Wilms
Jonas Wilms

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

Related Questions