Home > Blockchain >  DataTables on click search per column
DataTables on click search per column

Time:12-11

I'm trying to active the seach per column on click of the related element.

I managed to get the search box on click but it doesn't perform the search

I'm not that expert with javascript and jQuery but this is my code:

    // Setup - add a text input to each footer cell
    $('#DataTable tfoot th').each(function () {

        var title = $(this).text();
        $(this).click(function (event) {
            $(this).html('<input type="text" placeholder="Search '   title   '" />');
            $(this).unbind('click');
        });

    });

    // DataTable
    var table = $('#DataTable').DataTable({
        initComplete: function () {
            // Apply the search
            this.api().columns().every(function () {
                var that = this;

                $('input', this.footer()).on('keyup change clear', function () {
                    if (that.search() !== this.value) {
                        that
                            .search(this.value)
                            .draw();
                    }
                });
            });
        }
    });

Is there also a way to make the code shorter?

Thank you

CodePudding user response:

The input doesn't exist at the point where you attach your keyup change clear event handler to it. You'll need to use delegated events instead.

initComplete: function() {
    this.api().columns().every(function() {
        var that = this;
        $(this.footer()).on('keyup change clear', 'input', function() {
            if (that.search() !== this.value) {
                that.search(this.value).draw();
            }
        });
    });
}

You can use jQuery's one method to attach an event handler which will only be called once. You should also avoid creating multiple jQuery wrappers for the same input where you can.

$('#DataTable tfoot th').each(function () {
    var $this = $(this);
    $this.one("click", function (event) {
        $this.empty().append($('<input/>').attr("type", "search").attr("placeholder", "Search "   $this.text()));
    });
});
  • Related