0

I have a dropdown menu and a javascript code which generates a table which is searchable, sortable on desktop. What I would like to do is to get a dropdown menu for the mobile users to select which column they would like to sort the data on as the table is responsive and no longer have the same view as on desktop. I have the following menu:

<select name="sortBy" id="sortBy" >
    <option value="">[ choose a column ]</option>
    <option value="0">Added</option>        
    <option value="1">Name</option>        
    <option value="2">Change (1hr) %</option>              
    <option value="3">Liquidity</option>              
</select>

Then I have the javascript:

$(document).ready(function () {
     var oTable = $('#dataTable').DataTable({
              "pageLength": 30,
              "paging": true,
              "lengthChange": false,
              "searching": true,
              "ordering": true,
              "order": [],
              "info": true,
              "autoWidth": true

              });

    $("#sortBy").change(function () {

        oTable.order([1, 'asc']).draw();
        })   

});

It is partially working is the dropdown sorts the table but using column 1 only. How can I get the option values across from the dropdown menu into the javascript so it dinamically sorts whatever selected. Something like:

$(document).ready(function () {
     var oTable = $('#dataTable').DataTable({
              "pageLength": 30,
              "paging": true,
              "lengthChange": false,
              "searching": true,
              "ordering": true,
              "order": [],
              "info": true,
              "autoWidth": true

              });

    $("#sortBy").change(function () {

        oTable.order([**VARIABLE**, 'asc']).draw();
        })
Zoltan75
  • 45
  • 1
  • 4
  • See [Get selected value of a dropdown's item using jQuery](https://stackoverflow.com/questions/2780566/get-selected-value-of-a-dropdowns-item-using-jquery). So, to get the value needed for `**VARIABLE**`, you can use this: `var colIdx = $('#sortBy :selected').val();`. And then you can use `table.order( [ colIdx, 'asc' ] ).draw();`. Or combine both lines into one. – andrewJames May 25 '21 at 12:29

1 Answers1

0

Many thanks for the help the whole corrected and working code is:

    $(document).ready(function () {
         var oTable = $('#dataTable').DataTable({
                  "pageLength": 30,
                  "paging": true,
                  "lengthChange": false,
                  "searching": true,
                  "ordering": true,
                  "order": [],
                  "info": true,
                  "autoWidth": true

                  });
        
        
        
        $("#sortBy").change(function () {
            var colIdx = $('#sortBy :selected').val();
            oTable.order([colIdx, 'asc']).draw();
            })   
});
Zoltan75
  • 45
  • 1
  • 4