2

How can I make each row clickable without repeating

This one is an example that shows the problem, parameter could be the code:

<table>
<thead>
    <tr>
        <th>Code</th>
        <th>User</th>
        ...
    </tr>
</thead>
<tbody>
    <tr>
        <td><a href="page/123"> 123 </a></td>
        <td><a href="page/123"> User A </a></td>
        ...
    </tr>
    <tr>
        <td><a href="page/456"> 456 </a></td>
        <td><a href="page/456"> User B </a></td>
        ...
    </tr>
</tbody>

Thanks Excuse me for my English, I hope that you understand the problem.

David
  • 503
  • 3
  • 7
  • 18

2 Answers2

4

There are a few different ways to achieve this. Here are a couple using plain javascript and one using jQuery.

Plain JS

With plain javascript with just use the onclick parameter. Pretty straight forward.

<table>
<thead>
    <tr>
        <th>Code</th>
        <th>User</th>
        ...
    </tr>
</thead>
<tbody>
    <tr onclick="window.location='page/parameter1';">
        <td> 123 </td>
        <td> User A </td>
        ...
    </tr>
    <tr onclick="window.location='page/parameter2';">
        <td> 456 </td>
        <td> User B </td>
        ...
    </tr>
</tbody>
</table>

jQuery

With jQuery you add a class so you can use that as the selector. There is also a data-href parameter that will hold the URL you want the user to go to when they click the row.

<table>
<thead>
    <tr>
        <th>Code</th>
        <th>User</th>
        ...
    </tr>
</thead>
<tbody>
    <tr class="clickable" data-href="page/parameter1">
        <td> 123 </td>
        <td> User A </td>
        ...
    </tr>
    <tr class="clickable" data-href="page/parameter2">
        <td> 456 </td>
        <td> User B </td>
        ...
    </tr>
</tbody>
</table>

<script>
    jQuery(document).ready(function($) {
        $("tr.clickable").click(function() {
            window.location = $(this).data("href");
        });
    });
</script>
slapyo
  • 2,979
  • 1
  • 15
  • 24
  • Yes! It works! Previously I found solutions similar to this but didn't work, I don't know why =S THANKS! – David Oct 28 '14 at 19:08
1

Your code should look like :

<table>
<thead>
    <tr>
        <th>Code</th>
        <th>User</th>
        ...
    </tr>
</thead>
<tbody>
    <tr>
        <td><a href="page/parameter1"> 123 </a></td>
        <td><a href="page/parameter1"> User A </a></td>
        ...
    </tr>
    <tr>
        <td><a href="page/parameter2"> 456 </a></td>
        <td><a href="page/parameter2"> User B </a></td>
        ...
    </tr>
</tbody>

Added end tag </a>

Carca
  • 564
  • 1
  • 6
  • 16