Individual column searching (select inputs) on data-order?

Individual column searching (select inputs) on data-order?

se3jayse3jay Posts: 1Questions: 1Answers: 0

Hi,
I'm using the following code to search on individual columns with a select inputs.

var table = $('#table_id').DataTable({
            initComplete: function () {
                this.api().columns([2]).every( function () {
                    var column = this;
                    var select = $('<select><option value="">Show All</option></select>')
                        .appendTo( $(column.header()) )
                        .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+'</option>' )
                    } );
                } );
            }
        });

However, the column I'm searching on contains a state and a city like so:

<td data-order="Georgia" data-search="{{ opp.State__r.Name }}">
    Columbus,
    Georgia
</td>

This causes all my select inputs to have both a city and state mentioned. I wondering, since I'm adding ordering on only the state of this column, would it be possible to modify my select inputs to only display and search on state like "Georgia" instead of "Columbus, Georgia"?

Thanks in advance!

This question has an accepted answers - jump to answer

Answers

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

    The code that builds the options list is this:

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

    The d variable is the cell value, ie Columbus, Georgia. You can parse the string to append only the state to the select options. The other thing you would need to do is make sure the state you are appending isn't already in the select options. I would consider using an array for this. Add each state to the array as you add them to the select. Then you can see if the state is in the array before adding to the select.

    Kevin

This discussion has been closed.