0

I was wondering how to load datatable api with default search value. I tried something like this.

$(document).ready(function{
    $('#datatable').DataTable();
    $("input[type=search]").val('john')
});

But since, in order to show the search results the search box needs to be submitted. How do I this ?

1 Answer 1

1

Try triggering a keyup event...

$(document).ready(function{
    $("#datatable").DataTable();
    $("input[type='search']").val("john").trigger("keyup");
});



EDIT

I found a way to disable the pagination when a search is active.
Meaning when the search input field isn't empty.

I refined my solution to also hide the unsefull controls, considering a no-pagination dataTable.

See it on CodePen.

searchField.on("input",function(){

    // Grab the seach term (text inputed in the search field)
    searchTerm = $(this).val();
    console.log("searchTerm: "+searchTerm);

    // The paginate links and buttons...
    var paginate = $("#myTable").siblings('.dataTables_paginate');

    // Remove the whole table when search term is empty.
    if(searchTerm==""){
        console.log("searchField: empty");

        // Set pagination to desired length
        // and show controls.
        myTable.page.len( paginationLength ).columns.adjust().draw();
        paginate.show();
        pageLenghtSelect.show();
    }else{
        console.log("searchField: NOT empty");

        // Set pagination to no pagination at all (only one page).
        // and hide controls.
        myTable.page.len( -1 ).columns.adjust().draw();
        paginate.hide();
        pageLenghtSelect.hide();

    }
});
Sign up to request clarification or add additional context in comments.

13 Comments

I just tryed on my side... It works with keyup and with input (the events), but doesn't with keydown or keypress.
Okay. I found another way to do it. $('#datatable').DataTable({ "paging": false, "oSearch": {"sSearch": searchText} }); I put the user typed value in the variable searchText But now, how do I turn the table to normal when the search box is cleared ?
Could you define «turn to normal»? Because, the way you've found is working too. I confirm. If «normal» refers to pagination being gone... Simply remove "paging": false, which disables pagination (it ain't helpfull in your search concern. ;)
I mean, after the user types in the search box, the pagination is gone. And I need the pagination back, when the search box is cleared. Sorry for my poor explanation.
Do you really want to disable the pagination for this first onload search ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.