I want to get the row id or index from a table by searching for a cell value and i dont know how. Please help me get going: :)
<button id="button" class="btn btn-secondary">Get index of row 2</button>
<table id="table">
<tbody>
<tr data-index="0">
<td>cell 1</td>
<td>cell 2</td>
<td>cell 3</td>
</tr>
<tr data-index="1">
<td>cell 4</td>
<td>cell 5</td>
<td>cell 6</td>
</tr>
<tr data-index="2">
<td>cell 7</td>
<td>cell 8</td>
<td>cell 9</td>
</tr>
</tbody>
</table>
var $table = $('#table')
var $button = $('#button')
var $SearchFor ='cell 5'
$(function() {
$button.click(function () {
alert('row id of '+$SearchFor+' is')
})
})
You can use the following:
$table.find("td:contains('"+$SearchFor+"')").parent().index();
or
$table.find("td:contains('"+$SearchFor+"')").parent().data("index");
Demo
var $table = $('#table') var $button = $('#button') var $SearchFor = 'cell 5' $(function() { $button.click(function() { var i = $table.find("td:contains('"+$SearchFor+"')").parent().index(); console.log($SearchFor + " is found in row with data-index " +i) }) })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="button" class="btn btn-secondary">Get index of row 2</button> <table id="table"> <tbody> <tr data-index="0"> <td>cell 1</td> <td>cell 2</td> <td>cell 3</td> </tr> <tr data-index="1"> <td>cell 4</td> <td>cell 5</td> <td>cell 6</td> </tr> <tr data-index="2"> <td>cell 7</td> <td>cell 8</td> <td>cell 9</td> </tr> </tbody> </table>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.