DaveLar DaveLar - 4 months ago 21
Javascript Question

Rewrite HTML using jQuery

I have table that looks like this:

<table>
<thead>
<tr>
<th>ID</th>
<th>Link</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>Link</th>
</tr>
</tfoot>
<tbody>
<tr>
<td>1</td>
<td><a href='#' onClick=('remove(0)')>Remove</a></td>
</tr>
<tr>
<td>2</td>
<td><a href='#' onClick=('remove(1')>Remove</a></td>
</tr>
<tr>
<td>3</td>
<td><a href='#' onClick=('remove(2)')>Remove</a></td>
</tr>
<tr>
<td>4</td>
<td><a href='#' onClick=('remove(3)')>Remove</a></td>
</tr>
<tr>
<td>5</td>
<td><a href='#' onClick=('remove(4)')>Remove</a></td>
</tr>
<tr>
<td>6</td>
<td><a href='#' onClick=('remove(5)')>Remove</a></td>
</tr>
</tbody>
</table>


Where the inparameter to remove() is the rownumber. In the remove function I'm removing the row, which means I need to rewrite the rownumbers if want to delete more than once before reloading the page. How can I achieve this using jQuery?

Answer

Remove the onclick from the rows and use jQuery. There is no need to rewrite something then.

$(document).on("click", "a.remove", function() {
    $(this).closest("tr").remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>1</td>
    <td><a class="remove" href='#'>Remove</a></td>
  </tr>
  <tr>
    <td>2</td>
    <td><a class="remove" href='#'>Remove</a></td>
  </tr>
  <tr>
    <td>3</td>
    <td><a class="remove" href='#'>Remove</a></td>
  </tr>
</table>

Comments