Retrieve information from the selected row within a table by pressing the Enter key

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! 😊

Answer â„–1

Expanding on the existing code you're working with, you have the option to include

if (key == 13 && selectedRow > 0)
    name = $rows.eq(selectedRow).find(">td").eq(0).text()

By utilizing .find(">td"), you specifically target the td cells, skipping over the initial th column and identifying the first td as 0.

The original code structure determines the selectedRow, hence I added 13 in the arrows array for consistency within the same if statement. This may seem unusual since it's not an arrow key, but maintaining the original method of selecting selectedRow was crucial based on your preference in a prior inquiry.

An alternative approach involves moving the enter key validation outside the arrow key array, using

$table.find('tbody tr.highlight_row > td').eq(0).text())

(refer to the second code snippet for this implementation)

$(function() {
  const UP = 38;
  const DOWN = 40;
  const ARROWS = [UP, DOWN, 13];
  const HIGHLIGHT = 'highlight_row';
  $('#searchbar').on('input keydown', function(e) {
    let $table = $('.child-div');
    $table.toggle($(this).val().length >= 1);

    let key = e.which;
    if (ARROWS.includes(key)) {
      let selectedRow = -1;
      let $rows = $table.find('tbody 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);
        
      } else if (key == 13 && selectedRow > 0) {
        alert($rows.eq(selectedRow).find(">td").eq(0).text())
        
      }
    }
    
    
  });
});
.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>

$(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');
    $table.toggle($(this).val().length >= 1);

    let key = e.which;
    if (ARROWS.includes(key)) {
      let selectedRow = -1;
      let $rows = $table.find('tbody 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);
        
      } 
    }
    
    if (key == 13) {
        var row = $table.find('tbody tr.highlight_row')
        alert(row.find(">td").eq(0).text())
    }
    
  });
});
.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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Controlling numerous websockets using React

I am currently developing a single-page application using React.js with a JSON RPC 2.0 backend API that relies on websockets. Managing multiple websocket connections simultaneously across different React.js components has been a challenge. Initially, I th ...

Submitting a form into a database with the help of AJAX within a looping structure

Trying to input values into the database using AJAX. The rows are generated in a loop from the database, with each row containing a button column. Clicking on the button submits the values to the database successfully. The issue is that it only inserts va ...

Ways to combine multiple CSS styles for an element using .css()

I'm struggling to apply styles to a deeply nested element using jQuery and JavaScript. I understand how to style nested elements, but I'm having trouble targeting a specific deeply nested element. My website is built on WordPress, and it has ins ...

How can one HTML form be used to request a unique identifier from the user, retrieve a record from the database, parse it into JSON format, and then populate an HTML page form using the

As someone who isn't an expert in any specific coding language, I have a knack for piecing things together to make them work. However, my current challenge is stretching my technical abilities a bit too far. Here's what I'm trying to achieve ...

What is the best way to re-render a component immediately following an update in React?

As I attempt to change the color of a bar to green and then back to black, it seems like the latter color update is taking precedence in my code. const [color, setColor] = useState("black") const bubbleSort = async () => { const sleep = ms => ...

Encountering an unhandled runtime error while importing the Client component into the server component: The JSON format is invalid, with the error message stating "undefined"

I've been attempting to create a basic counter component that increments the count of a state variable when a button is clicked. To achieve this, I created a separate file named Counter.tsx and placed it in the components folder at the root of my next ...

Finding the Biggest Number in an Array

I've come up with a solution using Math.max(), but I'm curious why the following approach isn't working. array = [4, 5, 1, 3] for (var i = 0; i < array.length; i++) { var num = 0; if (array[i] > num) { num = array[i]; } } ...

The functionality of -moz-background-clip:text is not functioning properly on Firefox browsers

Struggling to incorporate an image into a text within an h1 tag. Here's what I've attempted: <div class="image_clip"> <h1> MY WONDERFUL TEXT </h1> </div> In the CSS file: .image_clip{ background: url(../images/defa ...

To proceed, the user must choose the YES option on the radio button, not the NO option, in the jQuery validation process

I need to implement a jQuery validate rule that mandates the selection of YES (not no) in order for the form to be validated. Users must agree to terms before submitting. If the user chooses "No," an error message should display and the form should not val ...

Having trouble accessing CSS images in JSF

Issue Details : I am currently facing a problem with setting menu background images in my JSF application using CSS properties. The file structure is as follows This is the CSS snippet Style.css #menu { height:35px; width:950px; backgrou ...

Guide on modifying values using both input fields and buttons at the same time

I am facing an issue with my input field that is designed to accept numbers. I want the value to be changed both via keyboard input and buttons. The buttons are functioning correctly unless I try to use keyboard input as well. For instance, if I enter 10 ...

Validating a form using HTML5 in a modal designed with Bootstrap

As a newcomer to jquery and javascript, I am facing a challenge. I want the form to open when the "Open Modal" button in the modal is clicked. After that, upon clicking 'Save' in the modal, I need it to validate the HTML5 form and if validation ...

Modifying JavaScript Objects

After referring to the discussion at , I encountered a challenge with my javascript ajax function that retrieves JSON data. My goal is to trigger different js events based on the key-value pairs of the JSON response, but unfortunately, I am facing diffic ...

Having trouble setting the backgroundImage in React?

Hi there! I'm in the process of crafting my portfolio website. My goal is to have a captivating background image on the main page, and once users navigate to other sections of the portfolio, I'd like the background to switch to a solid color. Alt ...

struggling with unexpected outcomes in jQuery

Having issues with jquery lib, can someone assist? Below is my HTML code: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { ...

pdfMake introduces a page breaking effect when the canvas is utilized with the type "line"

Can anyone shed some light on why a canvas declaration with the type "line" is causing a page break in the generated PDF? I've tried removing all canvases and the page break disappears, but I can't identify the root cause. Any insights would be ...

Create an array of objects in JavaScript using JSON data

I have fetched a collection of dictionaries from my API: The data can be retrieved in JSON format like this: [{"2020-03-11 14:00:00":10.765736766809729} ,{"2020-03-11 15:00:00":10.788090128755387}, {"2020-03-11 16:00:00":10.70594897472582}, {"2020-03-11 1 ...

Guide to loading data into fullcalendar with ajax requests

Having some trouble with the fullcalendar plugin. I can't seem to retrieve data from my database using ajax. Here's the function I'm working with: function fetchCalendarData() { $.ajax({ type: 'get', u ...

Creating a message sniping command with Discord.js

I'm having trouble getting my bot to log/snipe a message when someone says 'zsnipe'. I want to make 'zsnipe' a command, but it's not working. Could you let me know what I'm doing wrong? Here is the code snippet: bo ...

Is there a way to incorporate a component into Particle.js?

I attempted to encase the Particle around the component but it's not functioning correctly import React from "react"; import { render } from "react-dom"; import Particles from "./Particles"; import "./index.css" ...