简体   繁体   中英

DataTables on click search per column

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

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()));
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM