Set selected item by default

Set selected item by default

m75sam75sa Posts: 132Questions: 30Answers: 0

I have the following example that works perfectly for me.

https://jsfiddle.net/4h0vyc45/55/

Just a question:
Is it possible to move the selected option menu on the right of the label? So next to the header label for example (not alone in the cel...) possible?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951
    Answer ✓

    One option is to remove the .empty() when using appendTo() to append the select to the th.
    https://jsfiddle.net/uoq39zmb/

    Kevin

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    you are the best, as ever! Thanks

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    @kthorngren I'm using with ajax/server side processing... but seems to doesn't work... any idea?

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    but seems to doesn't work... any idea?

    What exactly doesn't work?

    Kevin

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    i should replicate the issue.. .it's strange because if i don't use ajax and server side processing it works. will try to replicate so i hope you can help me
    thanks in advance

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    hi, back again

    this is the function that works when datas are not called via ajax (server side) but it doesn't when I use ajax...

    $(function () {
    
    var dataTable = $('#example-grid').DataTable( {
      "ajax":{
               url :"example-grid-data.php",
               type: "post", 
               error: function(){ 
                 $(".example-grid-error").html("");
                 $("#example-grid").append('<tbody class="example-grid-error"><tr><th colspan="3">Nessun dato presente.</th></tr></tbody>');
                 $("#example-grid_processing").css("display","none");
    
               }
             },
    
    initComplete: function() {
    
    this.api().columns([7]).every(function() {
    
    var column = this;
    var c = column[0];
    var select = $('<select style="display: block; " class="col'+c+'"><option value="">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) {
      var val = $('<div/>').html(d).text();
      select.append('<option value="' + val + '" selected>' + val + '</option>');
    
    });
    
    
    if (column[0] == 7) { 
      var valforcol = '';
      $(".col7").val(valforcol).change();
     column.search(valforcol ? '^' + valforcol + '$' : '', true, false).draw() 
    }
    
    
    });
    
    
    this.api().columns([0]).every(function() {
    var column = this;
    $('input', this.header()).on('keyup change', function() {
      if (column.search() !== this.value) {
        column
          .search(this.value)
          .draw();
      }
    });
    });
    
    },
    
    
    stateSaveParams: function (settings, data) {
    delete data.search;
    },
    order: [[2, 'asc']],
    "language": {
      "lengthMenu": "_MENU_",
      "paginate": {
                     "previous": "<i class='fas fa-chevron-circle-left'></i>",
                     "next": "<i class='fas fa-chevron-circle-right'></i>"
                  },
    
    "info": "Voci in elenco: _TOTAL_ ",
    "zeroRecords": "Nessuna voce presente",
    "search": "Cerca",
    "infoFiltered":   "",
    "infoEmpty":      "",
    "searchPlaceholder": "cerca...",
    
    
    "search": "",
    },
    responsive: true,  
    "autoWidth": true,
    bInfo: false,
    dom: '<"top"><"clear"><B><"right"lf>rt<"bottom"p><"clear">'
    ,
    
    buttons: [
    
    { extend: 'print', text: '<i class="fas fa-solid fa-print"></i> STAMPA' },
    
    
    ],
    
    "processing": true,
    "serverSide": true,
    "columnDefs": [ {
    "targets": [0,7],
    "orderable": false
    } ],
    "pageLength": 25,
    "paging": true,
    }).buttons().container().appendTo('#example_wrapper .col-md-6:eq(0)');
    
    
      });
    
  • m75sam75sa Posts: 132Questions: 30Answers: 0
    $(function () {
    
    var dataTable = $('#example-grid').DataTable( {
      "ajax":{
               url :"example-grid-data.php",
               type: "post", 
               error: function(){ 
                 $(".example-grid-error").html("");
                 $("#example-grid").append('<tbody class="example-grid-error"><tr><th colspan="3">Nessun dato presente.</th></tr></tbody>');
                 $("#example-grid_processing").css("display","none");
    
               }
             },
    
    initComplete: function() {
    
    this.api().columns([7]).every(function() {
    
    var column = this;
    var c = column[0];
    var select = $('<select style="display: block; " class="col'+c+'"><option value="">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) {
      var val = $('<div/>').html(d).text();
      select.append('<option value="' + val + '" selected>' + val + '</option>');
    
    });
    
    
    if (column[0] == 7) { 
      var valforcol = '';
      $(".col7").val(valforcol).change();
     column.search(valforcol ? '^' + valforcol + '$' : '', true, false).draw() 
    }
    
    
    });
    
    
    this.api().columns([0]).every(function() {
    var column = this;
    $('input', this.header()).on('keyup change', function() {
      if (column.search() !== this.value) {
        column
          .search(this.value)
          .draw();
      }
    });
    });
    
    },
    
    
    stateSaveParams: function (settings, data) {
    delete data.search;
    },
    order: [[2, 'asc']],
    "language": {
      "lengthMenu": "_MENU_",
      "paginate": {
                     "previous": "<i class='fas fa-chevron-circle-left'></i>",
                     "next": "<i class='fas fa-chevron-circle-right'></i>"
                  },
    
    "info": "Voci in elenco: _TOTAL_ ",
    "zeroRecords": "Nessuna voce presente",
    "search": "Cerca",
    "infoFiltered":   "",
    "infoEmpty":      "",
    "searchPlaceholder": "cerca...",
    
    
    "search": "",
    },
    responsive: true,  
    "autoWidth": true,
    bInfo: false,
    dom: '<"top"><"clear"><B><"right"lf>rt<"bottom"p><"clear">'
    ,
    
    buttons: [
    
    { extend: 'print', text: '<i class="fas fa-solid fa-print"></i> STAMPA' },
    
    
    ],
    
    "processing": true,
    "serverSide": true,
    "columnDefs": [ {
    "targets": [0,7],
    "orderable": false
    } ],
    "pageLength": 25,
    "paging": true,
    }).buttons().container().appendTo('#example_wrapper .col-md-6:eq(0)');
    
    
      });
    

    I can see the select option menu but it doesn't filter...

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    With server side processing the filtering is done at the server script. Are you using a Datatables supplied server side processing script?

    Kevin

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    yes, mysql db

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    can you help me with a sample so i can adapt? Thanks a lot

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    Which Datatables server side processing script are you using? It should support column searching.

    Have you verified the Ajax request is sent to the server when using selecting a search option?

    Have you verified the event hander fires when selecting a search option?

    Can you post a link to your page or a test case replicating the issue so we can take a look?
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    the problem is that the test case doesn't read remote ajax file...
    can i send you the .php called from ajax ?

  • m75sam75sa Posts: 132Questions: 30Answers: 0
    <?php
    require_once '_inc/_db.php';
    setlocale(LC_TIME, 'ita', 'it_IT.utf8');
    
    $conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
    $requestData= $_REQUEST;
    $columns = array( 
        0 => 'item name', 
        1 => 'date_cnt', 
        2 => 'surname', 
        3 => 'iso', 
        4 => 'movement',
        5 => 'cnt',
        6 => 'location',
        7 => 'typetr',
        8 => 'fcd',
        9 => 'sts',
        10 => ''
    
    );
    
    
    $datagrid = "wm_fleet";
    $tbl = "wbf";
    
    $sql = "SELECT * FROM " .$tbl;  
    $query=mysqli_query($conn, $sql) or die($datagrid."-im-grid-data.php: get ".$datagrid."-im1");
    $totalData = mysqli_num_rows($query);
    $totalFiltered = $totalData; 
    
    $qr = $_REQUEST['search']['value'];
    $qr = addslashes($qr);
    
    
    if (!empty($requestData['search']['value'])) {
    
        $sql = "SELECT * FROM (SELECT t1.* FROM wbf t1 WHERE t1.id = (SELECT MAX(t2.id) FROM wbf t2 WHERE t2.nr_contenitore = t1.nr_contenitore)) as my_table_tmp WHERE 1=1 and nr_contenitore LIKE '%".$qr."%'  "; 
    
    }
    else {
        $sql="SELECT * FROM (SELECT t1.* FROM wbf t1 WHERE t1.id = (SELECT MAX(t2.id) FROM wbf t2 WHERE t2.nr_contenitore = t1.nr_contenitore) order by nr_contenitore asc) as my_table_tmp";
    
    }
    
    
    
    
    $query=mysqli_query($conn, $sql) or die($datagrid."-im-grid-data.php: get ".$datagrid."-im2");
    $totalFiltered = mysqli_num_rows($query); 
    
    $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']." ";
    $query=mysqli_query($conn, $sql) or die($datagrid."-im-grid-data.php: get ".$datagrid."-im3");
    
    $data = array();
    function checkIsAValidDate($myDateString){
        return (bool)strtotime($myDateString);
    }
    while( $row=mysqli_fetch_array($query) ) { 
       $nr_contenitore = $row["nr_contenitore"];
       $nestedData=array(); 
    
      // DATA_CNT
      if ($row["date_cnt"]>0) {
    
        $crdatecnt=date_create(date($row["date_cnt"]));
        $crdatecnt=date_format($crdatecnt,"d/m/Y H:i");
        $data_cnt = $crdatecnt;
    } else {
        $data_cnt = '';
    }; 
            0 => 'item name', 
        1 => 'date_cnt', 
        2 => 'surname', 
        3 => 'iso', 
        4 => 'movement',
        5 => 'cnt',
        6 => 'location',
        7 => 'typetr',
        8 => 'fcd',
        9 => 'sts',
        10 => ''
    
    
    $cntm =strtoupper($row["nrcont"]);
    $iso =strtoupper($row["iso"]);
    $fcd =strtoupper($row["fcd"]);
    $movement = strtoupper($rsf["movement"]);
     };
    
    
    
    $nestedData[] = $cntm;
    $nestedData[] = $iso;
    $nestedData[] = $fcd;
    $nestedData[] = $movement;
    $nestedData[] = $fcd;   
    $nestedData[] = $fcd;
    $nestedData[] = $fcd;
    $nestedData[] = $fcd;
    $nestedData[] = $fcd;
    $nestedData[] = $fcd;
    $data[] = $nestedData;
    
    }
    
    $json_data = array(
                "draw"            => intval( $requestData['draw'] ),  
                "recordsTotal"    => intval( $totalData ), 
                "recordsFiltered" => intval( $totalFiltered ), 
                "data"            => $data 
                );
    
    
    
    echo json_encode($json_data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE);
    
    ?>
    
  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    Please provide details of what is not working and the troubleshooting you have done. Just posting code and saying it doesn't work does not provide enough details for us to help.

    Kevin

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    agree, the problem is that it doesn't filter... so i can see the select option menu but when i change the item it loads for a second and the nothing changes...
    I would like to replicate the issue with the testing code but the ajax call doesn't work on the testing area...

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    I don't use PHP and not familiar with it so I might be missing something but it doesn't look like your script is processing and using the column search values sent to the server. See the SSP Protocol docs for details.

    Take a look at the ssp.class.php script used in the SSP examples. Maybe look at using the Editor libraries as described in this blog.

    Kevin

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    I see this example:
    https://datatables.net/examples/server_side/simple.html

    now if i want to replicate it on jsbin or similar test case platform it doesn't work.

    But maybe i found a way. Starting from this sample, if i need to filter the first column with a select option ?
    In this way i can have a server side processing datas and the filtered function i need...
    can you help me on this?

  • m75sam75sa Posts: 132Questions: 30Answers: 0

    or in addition i found this that uses ajax call:
    http://live.datatables.net/gihuqawi/5/edit

    now if i want to add a select option on the first or second column?

  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951

    now if i want to replicate it on jsbin or similar test case platform it doesn't work.

    You can get SSP templates here.

    Kevin

  • m75sam75sa Posts: 132Questions: 30Answers: 0
    edited November 2022

    i cannot find a way how to solve...
    can you help me to add a filter here?
    http://live.datatables.net/gihuqawi/5/edit
    sorry and thanks

Sign In or Register to comment.