Thursday, March 9, 2017

Populate DropDown List from DataTables data for Column Name

For the project which I am working on I am using DataTables for easy filtering etc. I am using the Laravel package yajra/laravel-datatables. What I would like is for one of my column names, to be a dropdown list of all the available data values. I now have a custom filter dropdown list that is outside of the datatables, but I think it would look nicer if it's in the DataTables. What I have tried now, was adding the code of the dropdown list into the <th></th> but this overlaps the sorting icon of datatables. The code which I have now:

View:

<th>
    <select name="category" id="category" class="custom-select">
    <option value="reset">- Categorie -</option>
    @foreach($adviceCategories as $category => $name)
        <option value=></option>
    @endforeach
    </select>
</th>

Javascript:

<script type="text/javascript">
    $(document).ready(function() {
        oTable = $('#advicePreparations-table').DataTable({
            "language" : {
                "url" : "//cdn.datatables.net/plug-ins/1.10.13/i18n/Dutch.json"

            },
            "processing": true,
            "serverSide": true,
            "ajax": {
                url: "",
                data: function (d){
                    d.name = $('input[name=name]').val();
                }
            },
            "columns": [
                {data: 'name', name: 'name'},
                {data: 'category', name: 'category'},
                {data: 'question_name', name: 'goal'},
                {data: 'mergeColumn', name: 'mergeColumn'},
                {data: 'autheur', name: 'autheur'},
                {data: 'active', name: 'active'},
                {data: 'acties', name: 'acties', orderable: false, searchable: false},
                {data: 'delete', name:'delete', orderable: false, searchable: false}
            ]
        });
        $('#search-form').on('submit', function(e) {
            oTable.draw();
            e.preventDefault();
        });
        $('#category').change(function () {
            var search = $(this).val();
            if ($(this).val() == 'reset') {
                oTable.search('').columns().search('').draw();
            } else{
                oTable.columns(1).search(search).draw();
        }
        });
    });
</script>

Could someone help me fill a dropdown list in JavaScript, based on the values in a column and render this populated dropdown list to a column name?



via Anna Jeanine

Advertisement