Eoghan Buckey Eoghan Buckey - 7 months ago 306
HTML Question

How do I get the current row index of my table using Jquery?

So I am trying to get the row index of my table using Jquery, however my code returns the same index number for every single row. I need to find the index to remove the selected row. However this code only removes the last value
What I have tried so far:

function updateCredentialList() {
var index = $('.existingCredential').find('tr').closest('tr').index();
var i = $('.existingCredential').find('tr:eq('+index+')').remove();
alert(index);
}


My table:

<c:choose>
<c:when test="${action == 'edit'}">
<td class="data">
<input type="hidden" name="pkAdminCredentials" value="${environment.pkAdminCredentialIds}">
<input type="hidden" name="dbCredentials" value="${environment.dbCredentialIds}">
<table class="existingCredential">
<tr>
<th>Primary?</th>
<th>Username</th>
<th>Password</th>
<th>ID</th>
</tr>
<c:forEach var="each" items="${environment.pkAdminCredentials}">
<tr>
<td class="edit">${each.primary ? 'Yes' : 'No'</td>
<td class="edit">${each.username}</td>
<td class="edit">${each.password}</td>
<td class="edit">${each.id}</td>
<td><a class="editCredential" class="openWindow" data-modal-id="existingCredential" data-credential-id="${each.id}">Edit</a></td>
<td><a href="#">Delete</a></td>
</tr>
</c:forEach>
</table>
</td>
</c:when>
</c:choose>

Answer

To get current index using jQuery one possibility is the function index.

Let's create a simple table with 3 rows and an onclick event handler for each row:

$(function () {
  
  $('table').find('tr').on('click', function(e) {
    $(this).data('isSelected', true);
    $(this).siblings().data('isSelected', false);
    $('#log').append('<p>Current Index Row is: ' + $('table').find('tr').index(this) + '</p>')
  });


  $('#btn').on('click', function(e) {
    var selectedRow = $('table').find('tr').filter(function(index, element) {
      return $(this).data('isSelected') == true;
    });
    if (selectedRow.length == 1) {
      selectedRow.remove();
    }
  });

});
table, th, td {
  border: 1px solid black;
  width: 30%;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>

<table>
    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
    </tr>
    <tr>
        <td>u1</td>
        <td>Jackson</td>
        <td>100</td>
    </tr>
</table>
<p>Click on a table row</p>
<button id="btn">Remove the selected ROW (click on it before)</button>
<div id="log"></div>