1

I would like to filter data in the table dynamically. Here is the example of the code:

search = "da";
data = {Range[100],ResourceFunction["RandomString"][{"a", "d", "e", "n", "r", "s"}, {100, 5}]} // Transpose;
Column@{
   InputField[Dynamic@search, String],
   Dynamic@search,
   Cases[data, {_, x_} /; StringContainsQ[x, search]] // TableView
 }

Its dynamically updates 'search' variable on the change of InputField, but not when I apply Cases filter. When I put 'Dynamic@search instead' of 'search' inside of 'StringContainsQ' it return the error message "Element da is not a valid string or pattern element in da". I will be appreciated if somebody could help me to solve the issue.

  • 2
    Cases doesn't know how to handle dynamic variables. You have to wrap Dynamic around the entire TableView to make it work, e.g. Column@{InputField[Dynamic@search, String], Dynamic@search, Cases[data, {_, x_} /; StringContainsQ[x, search]] // TableView // Dynamic}. This way, the entire view will be recreated every time search changes – Lukas Lang Nov 17 '22 at 16:26
  • 1
    Try Dynamic with the Column: Dynamic@Column@{ InputField[Dynamic@search, String] , search , TableView[Cases[data, {_, x_} /; StringContainsQ[x, search]]] } – Syed Nov 17 '22 at 16:33

1 Answers1

3

Try:

search = "da";
SeedRandom[1];
data = {Range[100], 
    ResourceFunction["RandomString"][{"a", "d", "e", "n", "r", 
      "s"}, {100, 5}]} // Transpose;
Column@{InputField[Dynamic[search], String], Dynamic@search, 
    Cases[data, {_, x_} /; StringContainsQ[x, search]] // TableView //
      Dynamic} // Print;

enter image description here

and with a different input of "aa":

enter image description here

Daniel Huber
  • 51,463
  • 1
  • 23
  • 57