Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table filter not working with backspaces

enter image description here

I'm working on reproducing a live filter box with handsontable based on the built in search functionality at http://docs.handsontable.com/0.15.0-beta6/demo-search-for-values.html.

Right Now I've got a basic setup working at http://jsfiddle.net/uL3L4teL/4/

As explained in the docs, In this code if you enter a search string, you get the matching cells outputted to the console using the following function:

Handsontable.Dom.addEvent(searchFiled, 'keyup', function (event) {
    var queryResult = hot.search.query(this.value);
    console.log(queryResult);
    // ...
});

I want to grab the rows in the data array that match the search string and filter the original data 'data' by the search string before redisplaying the table. This partially works using:

Handsontable.Dom.addEvent(searchFiled, 'keyup', function (event) {
  // debugger
  hot.loadData(tData);

  var queryResult = hot.search.query(this.value);
  rows = getRowsFromObjects(queryResult);
  console.log('searchFiled',searchFiled.value);
  console.log('rows',rows);

  console.log('tData', tData);
  var filtered = tData.filter(function (d, ix) {
      return rows.indexOf(ix) >= 0;
  });
  console.log('filtered', filtered);

  hot.loadData(filtered);

});

However when I run this I see the following in the console when I enter 'n' followed by backspacing (to empty the searchstring):

enter 'n':

rows [0, 1]
searchFiled n
rows [0, 1]
tData [Array[4], Array[4], Array[4], Array[4]]
filtered [Array[4], Array[4]]

backspace (to empty search value):

rows []
searchFiled 
rows []
tData [Array[4], Array[4], Array[4], Array[4]]
filtered []

How can I fix this so an empty string will again show the entire unfiltered table?

like image 688
user1592380 Avatar asked Dec 04 '25 15:12

user1592380


1 Answers

You could add a condition inside of the .filter() method that will return all rows if the value searchFiled.value is empty or undefined:

Updated Example

var filtered = tData.filter(function(_, index) {
  if (searchFiled.value) {
    return rows.indexOf(index) >= 0;
  } else {
    return true;
  }
});

Alternatively, here is a one-liner that does the same thing (although it is less readable):

Updated Example

var filtered = tData.filter(function(_, index) {
  return !searchFiled.value || rows.indexOf(index) >= 0;
});
like image 146
Josh Crozier Avatar answered Dec 06 '25 03:12

Josh Crozier