How can I use the events to hide the datatables until I get a results from the search filters?

How can I use the events to hide the datatables until I get a results from the search filters?

amazeinstudios@gmail.comamazeinstudios@gmail.com Posts: 35Questions: 6Answers: 0
edited November 2019 in Free community support

I am currently building a datatable that has a custom search query as an ajax filter and that works great. What I want to master is a way to hide the table on the loading of a the page just to show the form. Once a user types in the search form the datatables will fade into view with the results. Secondly, when the user empties all of the search queries allow the form to once again fade out of view. I do want to show if there aren't any matching entries some kind of way. An example of the code is below:

<head>
<title></title>
<meta charset="utf-8" />
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css">

</head>
<body style="width:500px;margin:auto;padding-top:50px">
    <table cellpadding="3" cellspacing="0" border="0" style="width: 67%; margin: 0 auto 2em auto;">
        <thead>
            <tr>
                <th>Target</th>
                <th>Search text</th>
            </tr>
        </thead>
        <tbody>
           
            <tr id="filter_col1" data-column="0">
                <td>Column - Name</td>
                <td align="center"><input type="text" class="column_filter" id="col0_filter"></td>
                
            </tr>
            <tr id="filter_col2" data-column="1">
                <td>Column - Age</td>
                <td align="center"><input type="text" class="column_filter" id="col1_filter"></td>
                
            </tr>
            <tr id="filter_col3" data-column="2">
                <td>Column - Sex</td>
                <td align="center"><input type="text" class="column_filter" id="col2_filter"></td>
                
            </tr>
            <tr id="filter_col4" data-column="3">
                <td>Column - Occupation</td>
                <td align="center"><input type="text" class="column_filter" id="col3_filter"></td>
                
            </tr>
           
        </tbody>
    </table><table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Sex</th>
                <th>Occupation</th>
            </tr>
        </thead>
      
        <tfoot>
            <tr>
                <th>Name</th>
                <th>Age</th>
                <th>Sex</th>
                <th>Occupation</th>
            </tr>
        </tfoot>
    </table>
    
    

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script>
    
 
function filterColumn ( i ) {
    $('#example').DataTable().column( i ).search(
        $('#col'+i+'_filter').val() 
    ).draw();
}
    
    $(document).ready(function () {
      $.ajax({
        url: "http://www.yogihosting.com/wp-content/themes/yogi-yogihosting/code/jsonp/persons.json",
        dataType: "jsonp", // jsonp
        type: "POST",
        jsonpCallback: 'processFunction', // add this property
        contentType: "application/json; charset=utf-8",
        success: function (result, status, xhr) {
          $('#example').DataTable({
            data: result,
            columns: [
              { data: 'name' },
              { data: 'age' },
              { data: 'sex' },
              { data: 'occupation' }
            ],
            "pageLength": 25
          });
        },
        error: function (xhr, status, error) {
          console.log("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        }
      });
        $('input.column_filter').on( 'keyup click', function () {
        filterColumn( $(this).parents('tr').attr('data-column') );
    } );
    });
 

    </script>
</body>

Edited by Kevin:  Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

Answers

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955
    Answer ✓

    I would take a look at using the search event. In the event use the page().info() to get the number of displayed rows (recordsDisplay). Use jQuery show() and hide() to display the div, defaulted to style="display:none;", that Datatables is in.

    Here is a simple example:
    http://live.datatables.net/tivogiga/1/edit

    Type more into the search box to clear all the rows and the Datatable is hidden.

    Kevin

  • amazeinstudios@gmail.comamazeinstudios@gmail.com Posts: 35Questions: 6Answers: 0

    Thanx for this.
    I guess what I am looking for is a tad simpler. How can I retrieve the event if form field is empty or not? One circumstance is if they type and get no results, the other is if they haven't typed or haved cleared the form. The third is when they type and receive results. So I need the event controlling when the form has been entered in. How do I identify that?

  • kthorngrenkthorngren Posts: 21,351Questions: 26Answers: 4,955
    Answer ✓

    How can I retrieve the event if form field is empty or not? One circumstance is if they type and get no results, the other is if they haven't typed or haved cleared the form.

    You would use standard Javascript/jQuery techniques to create an event handler and evaluate the form data. Its not a Datatables controlled form.

    The third is when they type and receive results.

    As shown in my example you can use page().info() to get the displayed row count. Another API option is table.rows( {search: 'applied'} ).count(). Where you place this depends no how you are doing the search. If using one of the Datatables search API's then the search is a good place. If you are fetching the data via Ajax and building a Datatable then in the initComplete might might be more appropriate.

    If this doesn't help then please post a running example of what you want so we can help fine tune it.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • amazeinstudios@gmail.comamazeinstudios@gmail.com Posts: 35Questions: 6Answers: 0
    edited November 2019

    Thanks again but simply I am just trying to locate the event of when a user types in the form... When a user types it fires the triggers a fallback to AJAX. When I find that my solution is complete.

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    I might be misunderstanding, but wouldn't that just be a standard keyup in the input element.

  • amazeinstudios@gmail.comamazeinstudios@gmail.com Posts: 35Questions: 6Answers: 0

    It could be ... but that is what I am asking - to identify the event of a user typing in the query field. Can I log these events to the console?

  • colincolin Posts: 15,240Questions: 1Answers: 2,599
    Answer ✓

    Yep, something like this: http://live.datatables.net/qatiriyu/1/edit

  • amazeinstudios@gmail.comamazeinstudios@gmail.com Posts: 35Questions: 6Answers: 0

    if (this).val()=="null" {
    console.log ("empty");
    };

    ....
    Please correct this for me

  • amazeinstudios@gmail.comamazeinstudios@gmail.com Posts: 35Questions: 6Answers: 0

    thanx sir

    $(document).ready( function () {
    var table = $('#example').DataTable();

    $('#example_filter input').on('keyup', function() {
    var key = $(this).val();
    console.log(key);
    if (key===""){
    console.log("empty");
    }
    });
    } );

  • PoorDevPoorDev Posts: 1Questions: 0Answers: 0
    edited February 2022

    empty table first

    db.search(null).draw()

    then

    use if (!this.value.length) condition

        $('#invno').on('keyup', function(e) {
                if (!this.value.length) {db.columns(0).search(null).draw(); return;}
                db
                    .columns(0)
                    .search(this.value)
                    .row({search: 'applied'})
                    .select()
                    .draw()
                ;
              }
        });
    
Sign In or Register to comment.