gridjs

Programatically search gridjs table (with javascript)


Using gridjs.io, I would like to perform a search when the gridjs table is initialized. More generally speaking, I would like to know how to programatically use the search without the user using the input field.

What I tried:

Example Code not working:

HTML

<div id="wrapper"></div>

Javascript

const grid = new Grid({
  columns: ['Name', 'Email', 'Phone Number'],
  search: true,
  data: [
    ['John', 'john@example.com', '(353) 01 222 3333'],
    ['Mark', 'mark@gmail.com',   '(01) 22 888 4444'],
    ['Eoin', 'eo3n@yahoo.com',   '(05) 10 878 5554'],
    ['Nisen', 'nis900@gmail.com',   '313 333 1923']
  ]
});
grid.render(document.getElementById("wrapper"));

// SEARCH/FILTER WITH JAVASCRIPT (NOT WORKING):
document.querySelector("input.gridjs-input").value = "John";

Result The grid should be filtered, but it still shows all rows. The filter event was not dispatched. How can I dispatch the event with javascript?

enter image description here


Solution

  • The input element has an input Event listener attached to it (Image)

    You can create and dispatch the event using this code:

    // Find the gridjs searchbox and set the value
    var el = document.querySelector('.gridjs-search-input');
    el.value = newVal;
    
    // Create and dispatch the event
    var event = new Event('input', {
        bubbles: true,
        cancelable: true,
    });
    el.dispatchEvent(event);