Row index retrieval in Datatable is not possible following a search operation

I have successfully created a datatable and can retrieve the row index of the data before any search action is performed.

dataArray=[
   [1, "Name1"],       
   [2, "Name2"], , 
   [3, "Name23"], 
];


var table = $('#tblName').DataTable( {
             scrollY:        '40vh',
             "scrollX": true,
             scrollCollapse: true,
             paging:         false,
             responsive:true,
             data: dataArray,
           } );
$('#tblName tbody').on( 'click', 'tr', function () {
    if ( $(this).hasClass('selected1') ) {
    }
    else 
    {
       $('#tblName tbody tr ').each(  function () {
          if ( $(this).hasClass('selected1') ) {
             $(this).removeClass('selected1');
           }
       } );
       $(this).addClass('selected1');
    }
} );

I aim to retrieve the row index in order to change the value of the dataArray. Input text searchName is provided to filter the datatable based on keyword matches with dataArray in column 1.

$('#searchName').on( 'keyup', function () {
   table
   .columns( 1 )
   .search( this.value )
   .draw();
} );

$('#tblName tbody').on( 'click', 'tr', function () {
   $('#tblName tbody tr ').each(  function () {
       if ( $(this).hasClass('selected1') ) {
           var rowindex=$(this).closest('tr').index();
           var dataWareHouse = table.row( this ).columns(1).data();
           var selectedName = dataArray[0][rowindex];
           console.log(selectedName);
       }
    } );
} );

After filtering the datatable with the input text searchName, I encounter an issue where I am unable to retrieve the correct old row index. For instance, upon entering '2' in searchName:

2

The datatable displays only 2 rows with the names Name2 and Name23. However, when clicking on the first row, it displays Name1 instead of Name2 which is the expected result.

Answer №1

When utilizing search features, relying on DOM index may not be accurate as some data may not be displayed due to filtering. However, DataTables offer API methods to obtain correct indices, data, and more.

$('#tblName tbody').on( 'click', 'tr', function () {
   $('#tblName tbody tr ').each(  function () {
       if ( $(this).hasClass('selected1') ) {
           var rowindex = table.row(this).index();
           var rowData = table.row(this).data();
           var selectedName = table.row(this)[0];
           var anotherWayToGetName = table.cell(rowIndex, 0).data();
           console.log(rowIndex, rowData, selectedName, anotherWayToGeName);
       }
    } );
} );

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

Could someone provide some clarification on this callback related to node.js?

With the abundance of node.js tutorials available showing how to create a server, it can be overwhelming as they are all coded in different ways. The question then arises - when should you write it one way versus another? Unfortunately, none of the tutoria ...

What is the process for changing CORS origins while the NodeJS server is active?

Currently, I am in the process of modifying the CORS origins while the NodeJS server is operational. My main goal is to replace the existing CORS configuration when a specific user action triggers an update. In my attempt to achieve this, I experimented w ...

The count of bits is not producing the anticipated result

Attempting to tackle the challenge of Counting Bits using JavaScript, which involves determining the number of set bits for all numbers from 0 to N, storing them in an array, and returning the result Let me provide an explanation Input: n = 5 ...

Deactivate certain choices in React Select

Encountering difficulties disabling specific options in a large list within a React Select component. A total of 6,500 options are loaded into the select element. Initially, there were issues with search functionality lagging, but this was resolved by impl ...

Avoid duplicating the use of the same controller in a page to prevent mirroring each other

I have implemented MVC partial controls on my page twice to handle search functionality. Each partial control has its own controller for searching, resulting in my page having two controllers with the same name. <div ng-app="app" ng-controller="MainCon ...

Creating a prototype function in JavaScript

I am attempting to create a JavaScript prototype function that replicates the Python syntax of 'a' in 'abc'. The function works correctly in one example, but not in another. Can you help me identify what mistake I made? String.proto ...

Issue arises when trying to implement sidebar navigation in Angular with Materialize CSS

Just starting my Angular journey and running into some trouble trying to set up a practical and responsive menu using SidebarNav and Dropdown. I used CLI to install and configure angular2-materialize and materialize-css. To create the menu, I made a comp ...

To streamline your shopping experience, simply input various product IDs into the designated textbox to add multiple items to your shopping

I am currently working on a feature for Magento that allows customers to input multiple product IDs in a text box and add them to their shopping cart. I have successfully implemented this functionality for a single product ID using the jQuery code below: ...

Can you suggest an alternative for the "return" statement within a "for loop" in order to retrieve all values from the loop?

When using numInOrder + " : " + nameInOrder;, the console only displays one value: "1 : a". However, I would like to see: "1 : a 2 : b 3 : c 4 : d 5 : e 6 : f" in the console.log output. Additionally, I do not want to use consol.log(numInOrder + " ...

Having difficulty grasping the concept of toggleClass and jQuery selectors

I am struggling to understand the getLiveSearchUsers function in my JS file. Could someone please help me? I don't quite grasp what selector[0] is and what toggleClass is doing here. $.post("includes/handlers/ajax_search.php", {query:value, userLogge ...

Add the div id to the script

Currently, I have a script set up where by clicking on a specific div (for example id=packtoa), it will add a class 'show' to listview items that have a matching class with the clicked div's id. While this system works well, I find myself n ...

What are the steps to showcase the content of a Typescript file on an HTML webpage?

We are looking to create a sample gallery with source code examples. Including typescript, html, and HTML files to showcase similar to the Angular.io component samples pages. Is there a way to extract the source code from a typescript file within our pro ...

Transferring information through AJAX and fetching through PHP

Below is my current AJAX code setup: optionScope.data().stage = 'b'; $.ajax({ url: "functions/contact.php", type: "post", data: {'stage': optionScope.data().stage}, success: function(data, status) { ...

Is there a way to trim the string after the second occurrence of an underscore?

I am faced with the task of extracting file names and types from a list of files in an object and displaying them in a table. The list of files is returned by the server in the format: timestamp_id_filename. For example: 1568223848_12345678_some_document. ...

Sending a Thunk to the store using Typescript

Within my primary store.ts file, the following code is present: const store = createStore( rootReducer, composeWithDevTools(applyMiddleware(thunk)) ); store.dispatch(fetchUser()); Upon initial rendering, an action is dispatched to fetchUser in ord ...

What is the process of sending a post request using axios to insert data into a database in React

I am currently working on a login system using mysql, axios, express, and react. The database connections are functioning properly, but I am encountering errors specifically with these two posts, displaying messages like "ERR_CONNECTION_REFUSED" and UNCAUG ...

Tips for changing input field type from "password" to "text" in Angular?

Is there a way to dynamically convert an input field with type="password" to type="text" in Angular? In my demo, I have two input fields labeled Mobile no and Re-enter mobile number. I want these fields to change to type="text" if the user inputs the same ...

Passing a variable through jQuery onClick event to a URL via GET request and subsequently loading the content of

After successfully passing variables through AJAX calls via onClick to a PHP file and loading the results on the initial page, I now face the challenge of passing a variable analogously via onClick to a PHP file but this time I need to either open a new wi ...

Steps for linking a page to a modal without embedding the page's content within the modal

Here is a snippet of code for a modal (from Twitter Bootstrap) that I am currently working with: <!-- Large Modal --> <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">Large Modal</button&g ...

Which codec strings are considered valid for the web codecs API?

I am searching for a definitive list of valid strings that can be passed as the `codec` parameter in `VideoEncoder.isConfigSupported({ codec, width, height })`, but I have been unable to find a clear answer so far: The TS declaration file states that it m ...