Can I make it so a dropdown filter doesn't need the specific option?

Can I make it so a dropdown filter doesn't need the specific option?

Tom98Tom98 Posts: 3Questions: 1Answers: 0

Hi there,

In one of my datatables, there's a column with 'status' which displays the status of a submission and the date of submission. For example: unread - 2022-05-26. I'd like to be able to sort this column by only the status, without taking the date into account. Of course, I could place the date in a separate column, but I think this would look a lot cleaner. Is it possible to change the filter as such?

Answers

  • kthorngrenkthorngren Posts: 20,269Questions: 26Answers: 4,765
    edited May 2022

    Guessing you are referring to the code in this column search example. This code builds the select list:

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

    You can use column().index() to if the column is the status column and if so use different code to get a unique list of statuses to populate the select options. Something like this pseudo code:

    if (column.index() === 3) {
      // Code to get unique list of statuses to append to the options list.
    } else {
      column
        .data()
        .unique()
        .sort()
        .each(function (d, j) {
           select.append('<option value="' + d + '">' + d + '</option>');
        });
    }
    

    Kevin

  • Tom98Tom98 Posts: 3Questions: 1Answers: 0

    Hi Kevin,

    Thanks for this example! I've got the right values in the dropdown now, but when using this dropdown to filter, it always returns no records. I guess this is the case because I'm trying to filter on 'unread', but the value in the table is 'unread - 2022-05-24' for example. Is it possible to only filter on the first part of the value in the table?

  • kthorngrenkthorngren Posts: 20,269Questions: 26Answers: 4,765

    By doing the same thing with the column().search(). In the example it uses this regex search:

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

    Maybe something like this would work for that particular column:

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

    The expectation is this will search for unread at the beginning of the string and match any characters after.

    Kevin

  • Tom98Tom98 Posts: 3Questions: 1Answers: 0

    That's it! Thanks so much for your help :)

Sign In or Register to comment.