I have a search box that dynamically populates a table. I am using arrow keys to navigate through the rows in the table. When I press the enter key, I want to retrieve the data from the selected row.
For example, in the code snippet below, I am trying to extract the name (e.g. John, Jacob) from the highlighted row.
$(function() {
const UP = 38;
const DOWN = 40;
const ARROWS = [UP, DOWN];
const HIGHLIGHT = 'highlight_row';
$('#searchbar').on('input keydown', function(e) {
let $table = $('.child-div');
if ($(this).val().length >= 3) {
$table.show();
} else {
$table.hide();
}
let key = e.which;
if (ARROWS.includes(key)) {
let selectedRow = -1;
let $rows = $table.find('tr');
$rows.each(function(i, row) {
if ($(row).hasClass(HIGHLIGHT)) {
selectedRow = i;
}
});
if (key == UP && selectedRow > 0) {
$rows.removeClass(HIGHLIGHT);
$rows.eq(selectedRow - 1).addClass(HIGHLIGHT);
} else if (key == DOWN && selectedRow < $rows.length - 1) {
$rows.removeClass(HIGHLIGHT);
$rows.eq(selectedRow + 1).addClass(HIGHLIGHT);
}
}
});
});
.highlight_row {
background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="text" class="form-control form-rounded rounded-pill" placeholder="Text input" id="searchbar">
<table class="table child-div" style="display: none;">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Mark</td>
<td>Otto</td>
<td>@mdo</td>
</tr>
<tr>
<th scope="row">2</th>
<td>Jacob</td>
<td>Thornton</td>
<td>@fat</td>
</tr>
<tr>
<th scope="row">3</th>
<td>Larry</td>
<td>the Bird</td>
<td>@twitter</td>
</tr>
</tbody>
</table>
</div>
How can I achieve this functionality successfully?
Thank you! 😊