Using columns vs column API

Using columns vs column API

andrewbellandrewbell Posts: 12Questions: 3Answers: 0

Hi. I've used the column searching example here (https://datatables.net/examples/api/multi_filter_select.html) and modified it to suit. This works fine.

                    this.api().columns([0]).every(function () {
                        var column = this;
                        var select = $('<select><option selected disabled>Choose Subnet</option></select>')
                            .appendTo($(column.header()).empty())
                            .on('change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );

                                column
                                    .search(val ? '^' + val + '$' : '', true, false)
                                    .draw();
                            });

                        column.data().unique().sort().each(function (d, j) {
                            select.append('<option value="' + d + '">' + d.substr(0,d.indexOf(" - ")) + '</option>')
                        });
                    });

Since I only want it to apply to one column, I thought it would be more logical to use the column API. But I cannot get this to work.

this.api().column(0) (function () {
...

Can anyone tell me where I'm going wrong?

Sorry I can't post a link, this is on an internal only network.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,309Questions: 26Answers: 4,947

    You should be able to remove the loop (lines 1 and 18) and just use var column = this.api().column(0) on line 2.

    Kevin

  • andrewbellandrewbell Posts: 12Questions: 3Answers: 0

    Thanks, that's what I assumed, but couldn't make work. I think I'm just missing the syntax to make it call a function.

  • kthorngrenkthorngren Posts: 21,309Questions: 26Answers: 4,947
    Answer ✓

    You don't need to make it a function. All you should need is this:

    initComplete: function () {
        var column = this.api().column(0);
        var select = $('<select><option selected disabled>Choose Subnet</option></select>')
            .appendTo($(column.header()).empty())
            .on('change', function () {
                var val = $.fn.dataTable.util.escapeRegex(
                    $(this).val()
                );
     
                column
                    .search(val ? '^' + val + '$' : '', true, false)
                    .draw();
            });
     
        column.data().unique().sort().each(function (d, j) {
            select.append('<option value="' + d + '">' + d.substr(0,d.indexOf(" - ")) + '</option>')
        });
    },
    

    Kevin

  • andrewbellandrewbell Posts: 12Questions: 3Answers: 0

    Brilliant, thank you!

This discussion has been closed.