Eoghan Buckey Eoghan Buckey - 1 year ago 586
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();

My table:

<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">
<c:forEach var="each" items="${environment.pkAdminCredentials}">
<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>

Answer Source

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) {

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

<p>Click on a table row</p>
<button id="btn">Remove the selected ROW (click on it before)</button>
<div id="log"></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download