How to programmatically get search results in an array
How to programmatically get search results in an array
kbessemer
Posts: 17Questions: 4Answers: 1
When using Data Tables, if a user types a phrase in the search box, is there a way to programmatically get the results of the search in an array?
Answers
Use
rows().data()
with theselector-modifier
of{ search: 'applied' }
to get the filtered row data. ChaintoArray()
to turn the result into a JS array. For example:Kevin
So this is working, somewhat. The behavior is off. The first time I run my function it returns an empty array, even though there is a search term and search results, but the second time I run the function it returns the proper array with the search results.
Without seeing what you are doing its hard to say. Maybe you need to use that code in an event like
search
. It really depends on what your goal is. Please provide a link to your page or a test case showing use what you are doing so we can offer suggestions.https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case
Kevin
I am using ReactJS, not sure if this is causing a problem... I tried using a search event and it isn't updating the variable with the search term
table.on( 'search.dt', function () {
searchPhrase = table.search();
} );
Honestly not sure how I would post my code in codepen since the react is JS and HTML combined
https://codesandbox.io/s/fervent-bogdan-wv07ry?file=/src/App.js:10293-11374
I'm not familiar with ReactJS. Looks like I need to install something from codesandbox.io to run the test case. So I didn't try that yet.
Here is a running example:
http://live.datatables.net/ciwakuwu/1/edit
Kevin
I changed my code to:
$(document).ready( function () {
} );
The search phrase is being passed to my other function properly... but after the function runs once the searchPhrase variable goes to undefined. And I have to type a phrase in the search box again.
And the search results are behaving the same in the array, the first time the function runs it is getting a big list of results, the 2nd time I run it, it's getting the correct results array
Ok, I managed to get something working for my situation...
I am not using the table.rows api for search results, that was not working for me.
But I am using a search event, and updating a redux store variable with the search phrase, then reading that store variable when I need to.
What is the problem? Did you try it in the
search
event like I suggested? Or are you using it somewhere else? Maybe your code snippet isn't accurate to how/where you are suing it.Kevin
Like Kevin I'm confused by that. The
rows()
method is the way to do exactly what you want.Allan