Reputation:
I need to select (highlight) specific table row (it is Bootstrap 4 table).
Here is sample code:
<p><a href="javascript:void(0);" onclick="select(3);">Select Row</a></p>
<table id="mtable" class="table table-hover b-t">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr id="tr1">
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr id="tr2">
<td>2</td>
<td>Otto</td>
<td>@TwBootstrap</td>
<td>123</td>
</tr>
<tr id="tr3">
<td>3</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr id="tr4">
<td>4</td>
<td>Larry the Bird</td>
<td>@twitter</td>
<td>abc</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
$('#mtable').on('click', 'tbody tr', function(event) {
$(this).addClass('highlight').siblings().removeClass('highlight');
});
function select(rowID){
// here I need to find tr3 and select it.
}
</script>
at the top I have a Link (select) and when clicked, I need that only row 3 is selected (highlighted). With other words, if some other row is selected, it should be unselected and only row 3 selected.
How to do that, please?
Thank you
Upvotes: 0
Views: 3710
Reputation: 5401
Since you are using jQuery, I removed the onclick
attribute. Then I added a data
attribute named id
, this is where you will put what id <a>
will be targeting.
$(function() {
$('a').on('click', function() {
var id = $(this).data('id');
$('tr').removeClass('highlight');
$('#row' + id).addClass('highlight');
})
})
.highlight {
background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><a data-id="1">Select Row 1</a></p>
<p><a data-id="2">Select Row 2</a></p>
<p><a data-id="3">Select Row 3</a></p>
<p><a data-id="4">Select Row 4</a></p>
<table id="mtable" class="table table-hover b-t">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr id="row1">
<td>1</td>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr id="row2">
<td>2</td>
<td>Otto</td>
<td>@TwBootstrap</td>
<td>123</td>
</tr>
<tr id="row3">
<td>3</td>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr id="row4">
<td>4</td>
<td>Larry the Bird</td>
<td>@twitter</td>
<td>abc</td>
</tr>
</tbody>
</table>
Upvotes: 1