Quantcast
Channel: Recent Discussions — DataTables forums
Viewing all 81395 articles
Browse latest View live

Question not posted.

$
0
0

Hi all, I am new to this community.
I had posted my first question 2-3 days ago. I edited out the question twice after submitting,the third time it was submitted to moderator for approval, I am not sure why. I cannot see the question in my profile nor does it show up anywhere as 'Pending Approval'. Is this an expected behavior?

Thanks!


Print the edit window

$
0
0

I have print, export functions working within Data Tables.

I would like to add print to the editor edit window (ie add print to formButtons) . I have the print button showing but no printing or exports happening within the Edit window

Any examples, pointers grateful

ie

        buttons: [
            { extend: "create", editor: editor},
            { extend: "edit",
                editor: editor,
                formButtons: [
                    {
                        label: 'Cancel',
                        fn: function () { this.close(); }
                    },
                    'Save row',
                    'print'
                ]
            },
            {
                extend: "selected",
                text: 'Duplicate',
                action: function ( e, dt, node, config ) {
                    // Start in edit mode, and then change to create
                    editor
                        .edit( table.rows( {selected: true} ).indexes(), {
                            title: 'Duplicate record',
                            buttons: 'Create from existing'
                        } )
                        .mode( 'create' );
                }
            },

etc

field names not escaped in php code when using serverside filtering

$
0
0

we have a table that uses serverside filtering.

the Editor PHP code is handling the serverside part of this table.

        $ed = Editor::Inst($db, 'mailbox_queue', 'index')
            ->fields(
                Field::inst('testbed'),
                Field::inst('link'),
                Field::inst('remarks'),
                Field::inst('date_add'),
                Field::inst('date_parsed')
            )
            ->$ed->process( $_POST )
            ->$ed->json();

Now this code first does a count on the table and generates below query

SELECT  COUNT(index) as 'cnt' FROM  `mailbox_queue`

inside the Count() function the field names are not escaped and mysql/mariadb errors on this.

The escaped query works

SELECT COUNT(`index`) as 'cnt' from mailbox_queue

I know index is a reserved keyword, but if escaped it should work, we are migrating a legacy application so we can not simply change the fieldname.

columns.render() - referencing a different column in render function

$
0
0

I'm trying to reference a separate column in the first "if" statement for the code below. I've tried every combination under the sun apart from the one that is correct apparently.

"data": "ErrorCount",
"render": function (data, type, row) {
                    var kTable = $('WTM_TABLE').DataTable();

                    if ( /*kTable.EndDate cell data for this row*/ == "9999-01-01T00:00:00") {
                        return '<i class="far fa-dot-circle" style="color:yellow"></i>';
                    }
                    if (data == 0) {
                        return '<i class="far fa-dot-circle" style="color:green"></i>';
                    }
                    return '<i class="far fa-dot-circle" style="color:red"></i>';
},

Thank you for your time,

Hiding search and lengthChange leaves empty divs behind

$
0
0

Hi,

I have the problem that when I set elements to false:

$.extend($.fn.dataTable.defaults, {
searching: false,
lengthChange: false
});

Then there are still empty divs being created:

Those are the divs that are the containers for search and lengthchange. They are now filling up empty space in height, which makes it ugly. Does anyone know if there is a solution for this?

Thanks, Asa

Multiple tables with same data source

$
0
0

I am creating a website with 8 datatables using a class. All tables are using the same data source. But each table has its own search/filter applied to display a subset of the the data source.

The datasource is loaded with an Ajax call and reloaded every 20 seconds.

I am noticing that the datasource, and therfore the api and its database, are being called very often. I was asuming it would be 1 Ajax call every 20 seconds. Or is it multiplied by 8?
If it is 8, than what would be a better solution? I do not want to make to many calls to the api/database.

A working example can be found here.
live.datatables.net/diragezu/1/edit

Error destroying table and re-create.

$
0
0

Hello friends,
I have some difficulties in developing my project, from which I can not destroy a table to create again with other columns and other data.

I can generate the table on the first try, but when I change the type of report I want to generate, because it has fewer columns than the initial one, it ends up generating error and does not exchange the data.

I'll be posting some screenshots about this:

Initial table:

Table with fewer columns:

What it was to show in the table with fewer columns:

My code:

$('#searchRel').on('click', function(e){
  
  if( $('#inputAteRel').val() !== '' &&  $('#inputDeRel').val() !== ''){
    e.preventDefault();

    $('#relName').html($('#nameOfRel').val());
    
    // filter
    var src = '';
    var col = [];
    var colDefs = [];
    var nameOfRel = $('#nameOfRel').val();
    if (nameOfRel == 'Ligações por Fila') {
        //headers = ['Fila', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '%Atend.', '%Não Atend.', '%Aband.'];
    }
    else if (nameOfRel == 'SLA por Fila'){
        //headers = ['Atendidas em até x Seg.', 'Atendidas', 'Não Atendidas', '%Atendidas', '%Não Atendidas', 'SLA'];
    }
    else if (nameOfRel == 'Ligações por Mês'){
      //headers = ['Mês', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '% Atend.', '%Não Atend.', '%Aband.'];
      src = 'timeCalls.months_calls';
      col = [{"title": "Mês", "data": "month", 'targets': 0},
              {"title": "Receb", "data": "receive", 'targets': 1},
              {"title": "Atend", "data": "awnsers", 'targets': 2},
              {"title": "Não Atend.", "data": "notAnswes", 'targets': 3},
              {"title": "Aband.", "data": "abandons", 'targets': 4},
              {"title": "Transf.", "data": "transfers", 'targets': 5},
              {"title": "Logins", "data": "logins", 'targets': 6},
              {"title": "Logoffs", "data": "logoffs", 'targets': 7},
              {"title": "Espera Média", "data": "avarege_wait_time", 'targets': 8},
              {"title": "Tempo Médio", "data": "avarege_conversation_time", 'targets': 9},
              {"title": "Atend.", "data": "porcentage_answers", "className": "porcentage", 'targets': 10},
              {"title": "Não Atend.", "data": "porcentage_notAnswers", "className": "porcentage", 'targets': 11},
              {"title": "Aband.", "data": "porcentage_abandons", "className": "porcentage", 'targets': 12}]
    }
    else if (nameOfRel === 'Ligações por Semana'){
        //headers = ['Semana', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '%Atend.', '%Não Atend.', '%Aband.'];
        src = 'timeCalls.week_calls';
    }
    else if (nameOfRel == 'Ligações por Dia'){
        tableId = 'ligDiaTable';
        src = 'timeCalls.days_calls';
        col = [{"title": 'Dia', 'data': 'day', 'targets': 0}, 
                {"title": 'Receb', 'data': 'receive', 'targets': 1}, 
                {"title": 'Atend.', 'data': 'awnsers', 'targets': 2}, 
                {"title": 'Não Atend.', 'data': 'notAnswes', 'targets': 3}, 
                {"title": 'Aband.', 'data': 'abandons', 'targets': 4}, 
                {"title": 'Transf.', 'data': 'transfers', 'targets': 5}, 
                {"title": 'Logins', 'data': 'logins', 'targets': 6}, 
                {"title": 'Logoffs', 'data': 'logoffs', 'targets': 7}, 
                {"title": 'Espera Média', 'data': 'avarege_wait_time', 'targets': 8}, 
                {"title": 'Tempo Médio', 'data': 'avarege_conversation_time', 'targets': 9}, 
                {"title": 'Atend.', 'data': 'porcentage_answers', 'className': 'porcentage', 'targets': 10}, 
                {"title": 'Não Atend.', 'data': 'porcentage_notAnswers', 'className': 'porcentage', 'targets': 11}, 
                {"title": 'Aband.', 'data': 'porcentage_abandons', 'className': 'porcentage', 'targets': 12}]
    }
    else if (nameOfRel == 'Ligações por Hora'){
      //headers = ['Hora', 'Receb.', 'Atend.', 'Não Atend.', 'Aband.', 'Transf.', 'Logins', 'Logoffs', 'Espera Média', 'Tempo Médio', '%Atend.', '%Não Atend.', '%Aband.'];
      src = 'timeCalls.hours_calls';
    }
    else if (nameOfRel === 'Ligações Atendidas'){
        src = 'answers_calls';
        col = [{'title': 'Agente', 'data': 'agent', 'targets': 0}, 
                {'title': 'Receb', 'data': 'receive', 'targets': 1},
                {'title': 'Complet', 'data': 'answer', 'targets': 2}, 
                {'title': 'Transf', 'data': 'tranfer', 'targets': 3}, 
                {'title': 'Chamad.', 'data': 'percentage_calls', 'className': 'porcentage', 'targets': 4}, 
                {'title': 'Tempo Convers.', 'data': 'time_conversation', 'targets': 5}, 
                {'title': 'Tempo Total', 'data': 'percentage_time', 'className': 'porcentage', 'targets': 6}, 
                {'title': 'Tempo Med. Convers.', 'data': 'average_conversation_time', 'targets': 7}, 
                {'title': 'Tempo Até Atend./Aband.', 'data': 'avarege_abandon_time', 'targets': 8}, 
                {'title': 'Tempo Med. Espera', 'data': 'avarege_wait_time', 'targets': 9}, 
                {'title': 'Maior Tempo Espera', 'data': 'high_wait_time', 'targets': 10}]
    }
    else if (nameOfRel === 'Ligações Não Atendidas'){
        src = 'notAnswers_calls';
        col = [{"title": "Fila", "data": "queue", 'targets': 0},
                {"title": "Total", "data": "receive", 'targets': 1},
                {"title": "Abandonadas", "data": "abandon", 'targets': 2},
                {"title": "Não Atendidas", "data": "notAnswer", 'targets': 3},
                {"title": "Chamadas", "data": "porcentage", "className": "porcentage", 'targets': 4}];
    }
    else if (nameOfRel == 'Ligações Abandonadas'){
        src = 'graphics.abandon.details';
        col = [{'title': 'Data', 'data': 'date', 'targets': 0},
               {'title': 'Numero', 'data': 'number', 'targets': 1},
               {'title': 'Tempo para Abandono', 'data': 'time', 'targets': 2}]
    }
    else if (nameOfRel == 'Ligações Transferidas'){
        src = 'graphics.tranfer.details';
        col = [{'title': 'Data', 'data': 'date', 'targets': 0},
                {'title': 'Numero', 'data': 'number', 'targets': 1},
                {'title': 'Origem', 'data': 'origin', 'targets': 2},
                {'title': 'Destino', 'data': 'destination', 'targets': 3}]
    }

    var data = {'src': src, 'col': col, 'colDefs': colDefs, 'dtPick': {'date_start': $('#inputDeRel').val(), 'date_end': $('#inputAteRel').val()}};

    // datatable header
    var theader = [];
    $(data.col).each(function(index, item){
      theader.push(item.title);
      var defs = {'title': item.title, 'targets': item.targets, 'visible': true};
      colDefs.push(defs);
    });

    var tHead = `<tr>
                    ${theader.map((th) => {
                        return '<th>'+th+'</th>';
                    }).join()}
                </tr>`;
    
    $('#tHead').html(tHead);
    $('#rel-chamadas').DataTable().destroy();
    // load datatable
    dtResults(data);

    // end
    $("html, body").animate({ scrollTop: $(document).height() }, "slow");
    $('#divRel').slideDown("slow");
    $.fn.dataTable.ext.errMode = 'none';
  };
});

function dtResults(data){
  $('#rel-chamadas').DataTable({
      "destroy": true,
      retrieve: true,
      dom: 'Bfrtip',
      buttons: [
          'excel', 'pdf'
      ],
      "ordering": false,
      "language":{
          "sEmptyTable": "Nenhum registro encontrado",
          "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
          "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
          "sInfoFiltered": "(Filtrados de _MAX_ registros)",
          "sInfoPostFix": "",
          "sInfoThousands": ".",
          "sLengthMenu": "_MENU_ resultados por página",
          "sLoadingRecords": "Carregando...",
          "sProcessing": "Processando...",
          "sZeroRecords": "Nenhum registro encontrado",
          "sSearch": "Pesquisar",
          "oPaginate": {
              "sNext": "Próximo",
              "sPrevious": "Anterior",
              "sFirst": "Primeiro",
              "sLast": "Último"
          },
          "oAria": {
              "sSortAscending": ": Ordenar colunas de forma ascendente",
              "sSortDescending": ": Ordenar colunas de forma descendente"
          }
      },
      "ajax": {
        "url": "<?= base_url('relatorios/aux_front'); ?>",
        "dataSrc": data.src,
        "dataType": 'json',
        "data": data.dtPick,
        "type": 'post',
        "error": function(response){
          console.error(response);
        }
      },
      "columns": data.col,
      "columnDefs": data.colDefs
  });
}

EDIT: Updated to use Markdown Code formatting.

Datatables stuck at loading when using ajax and webmethod

$
0
0

I'm trying to populate a datatables table with data from an SQL query from inside a C# webmethod. After days of researching and trial and error, I still can't seem to get it to work. Most of the examples I see are performing server-side rendering but my dataset is relatively small so client-side should be adequate. If I switch to using hard-coded 'data' variable, everything works.

I suspect the issue lies within the string type being returned from the webmethod. Despite verifying properly formatted JSON string being returned, the table doesn't render. Even if I hard-code a properly formatted JSON string in the webmethod (bypassing the query), I still get the same, renderless, result. I tried passing back an object but that didn't work either.

I'm stuck and at wits-end.

Code snipets at: http://live.datatables.net/lurujefi/1/edit?html,css,js. FYI, my c# code is in the CSS window.


Creating Multiple Child Rows [HTML/PHP/jQuery]

$
0
0

I have a DataTable that has hidden child rows to show extra information. Each parent row shows information about a gift card and the hidden children show a log of that gift card. A gift card could have 0+ logs.

For example:

  • Gift Card 1: 0 rows; the gift card has only been created (isn't logged), nothing else
  • Gift Card 2: 2 rows: the gift card has been redeemed once for $10 and another, separate time, for $15

My issue is the table creates a child for only the first log of any given GC. I need it to create a child for each and every log for that GC.

I know my code specifically targets [0] in the array, I just don't know how to go about making the required changes to do what I want.

The following is my table in HTML/PHP:

<table id='giftCertInfo' class='table table-striped'>
   <thead>
        <tr>
            <th></th>
            <th>Gift Cert #</th>
            <th>Gift Card #</th>
            <th>Issue Date</th>
            <th>Amount</th>
            <th>Balance</th>
            <th>Customer Name</th>
            <th>Status</th>
        </tr>
    </thead>

    <tbody>
        <?php
            foreach ($allGiftCertsList as $value) {
                $giftCertLogQuery = pg_execute($rs_conn, "gift_cert_log", array($value['all_gift_cert_id'], $value['gift_card_id']));
                $giftCertLogList = pg_fetch_all($giftCertLogQuery);

                if (pg_num_rows($giftCertLogQuery) > 0) {
                    echo "<tr data-child-value-1='" . $giftCertLogList[0]['all_gift_cert_id'] . "' data-child-value-2='" . $giftCertLogList[0]['adj_date'] . "' data-child-value-3='" . $giftCertLogList[0]['adj_type'] . "' data-child-value-4='" . $giftCertLogList[0]['amount'] . "' data-child-value-5='" . $giftCertLogList[0]['note'] . "'>";
                        echo "<td class='details-control'></td>";
                        echo "<td class='col-xs-2'>" . $value['all_gift_cert_id'] . "</td>";
                        echo "<td class='col-xs-2'>" . $value['gift_card_id'] . "</td>";
                        echo "<td class='col-xs-2'>" . date("D, M. j, Y", strtotime($value['issue_date'])) . "</td>";
                        echo "<td class='col-xs-1'>$" . $value['amount'] . "</td>";
                        echo "<td class='col-xs-1'>$" . $value['balance'] . "</td>";
                        echo "<td class='col-xs-2'>" . $value['customer_name'] . "</td>";
                        echo "<td class='col-xs-1'></td>";
                    echo "</tr>";
                } else {
                    echo "<tr>";
                        echo "<td class='col-xs-1'></td>";
                        echo "<td class='col-xs-2'>" . $value['all_gift_cert_id'] . "</td>";
                        echo "<td class='col-xs-2'>" . $value['gift_card_id'] . "</td>";
                        echo "<td class='col-xs-2'>" . date("D, M. j, Y", strtotime($value['issue_date'])) . "</td>";
                        echo "<td class='col-xs-1'>$" . $value['amount'] . "</td>";
                        echo "<td class='col-xs-1'>$" . $value['balance'] . "</td>";
                        echo "<td class='col-xs-2'>" . $value['customer_name'] . "</td>";
                        echo "<td class='col-xs-1'></td>";
                    echo "</tr>";
                }
            }
            unset($value);  // Unset the foreach value
        ?>
    </tbody>
</table>

And the following jQuery to do the child rows:

function format(gc_id, date, type, amount, note) {
    return "<div class='col-xs-offset-1'><b>GC ID:</b> " + gc_id + "</div><div class='col-xs-offset-1'><b>Date:</b> " + date + "</div><div class='col-xs-offset-1'><b>Type:</b> " + type + "</div><div class='col-xs-offset-1'><b>Amount:</b> " + amount + "</div><div class='col-xs-offset-1'><b>Note:</b> " + note + "</div>";
};

$(document).ready(function(){
    var table = $('#giftCertInfo').DataTable({
        "order": [[6, "asc" ], [3, "asc"]]
    });

    // Add event listener for opening and closing details
    $('#giftCertInfo').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);

        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        } else {
            // Open this row
            row.child(format( tr.data('child-value-1'), tr.data('child-value-2'), tr.data('child-value-3'), tr.data('child-value-4'), tr.data('child-value-5') )).show();
            tr.addClass('shown');
        }
    });
});

This is what it looks like now:

This is what it looks like now

And this is what I want it to look like:

And this is what I want it to look like

calculate footer row average and display on a different page

$
0
0

Hello

i have a question and maybe somebody could point me in the right direction.
I would like to display the total average of running time calculated from a footerCallback
i prepared a fiddle where you can see the footer callback displayed as column average for the displayed table and total table. what i would like to do is sum all (total) values from the footer row and divide these by the number off compressors to receive an overall average. Future i would like to display the overall average on a different page if possible. for example '(' + parseFloat(theColumnTotal / columnDataTotal.count()).toFixed(2) + ' Total)' / 5 = total average

Any help would be appreciated

Best regards
pascal

Don't activate select if clicking on a link

$
0
0

I'm configuring a datatable to use the slick multi-select option:

select: {
   style:     'multi',
   className: 'site-selected'
},

But within the datatable there's a link that opens in a new window, to allow someone to view the full record before deciding to select it. But clicking on that link also selects the row, making for a confusing experience for the user.

Basically I'd like to be able to indicate to datatables to NOT select the row when certain element types are selected. Is this possible? Or even exclude certain columns.

Thanks.

Custom dropdown button

$
0
0

I'd like to have a dropbown button to use for filtering on a key column. Ideally, there's be a way for me to create a custom dropdown button, but that doesn't seem to exist.

Alternatively, I could create a dropdown and then append it to the end of the other custom buttons. But I'm having a hard time figuring out the javascript to do that. I want to create the dropdown, then probably do a jquery('#myButton').insertAfter('last-custom-button'). The last custom button doesn't have an id, is there a way to set it? Or get the last button?

Options for Select Field Type - Default Drop-Down List Value

$
0
0

I would like to highlight/select the option in the drop-down list to match the value already returned in the column. I have not been successful in getting def to work. Should it be a placeholder?

fields: [
             {
                 label: "RATINGCODE",
                 name: "RATINGCODE",
                 type: "select",
                 options: [
                    <cfoutput query="codes">
                    { label: "#codes.ratingcode#", value: "#codes.ratingcodeid#"},
                    </cfoutput>
                 ]
             }

Text Field - Rich Text Editor

$
0
0

Has anyone had success with a rich text editor in their text field and/or a way to set the field to html?

Server-side Processing Load Data Very Slow

$
0
0

Hi,
I am using server-side DataTables for works with 2000++ rows. but, loading data when page is load, change order column, go to other table page and doing searching is too slow.

DataTables version i am using is 1.10.19 with bootstrap 3 style and CodeIgniter 3.

HTML :

<table id="site-table" class="table table-striped table-bordered" style="width:100%">
  <thead>
    <tr>
      <th style="width:5%">No</th>
      <th>SITE ID</th>
      <th>WID</th>
      <th>SITE NAME</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

JS :

var site = $('#site-table').DataTable({
    "destroy": true,
    "processing":true,
    "serverSide":true,
    "order":[],
    "ajax":{
        url:"<?php echo base_url().'Atp/getSiteList'; ?>",
        type:"POST"
    },
    "columnDefs":[
        {
          "targets":[0],
          "orderable":false,
        },
    ],
    "aoColumns":[
      null,
      null,
      null,
      null
    ],
  });

Controller :

public function getSiteList()
{
  $fetch_data = $this->M_ATP->getSiteList();
  $data = array();
  $no = 1;
  foreach($fetch_data as $row)
  {
    $sub_array = array();
    $sub_array[] = $no++;
    $sub_array[] = '
      <a href="'.base_url().'site_detail/'.$row->site_id_actual.'" target="_blank">'.$row->site_id_actual.'</a>
    ';
    $sub_array[] = $row->wid;
    $sub_array[] = $row->site_name;
    $data[] = $sub_array;
  }
  $output = array(
    "draw"                =>     intval($_POST["draw"]),
    "recordsTotal"        =>     $this->M_ATP->getSiteListNumRows(),
    "recordsFiltered"     =>     $this->M_ATP->getSiteListFilteredData(),
    "data"                =>     $data
  );
  echo json_encode($output);
}

Model :

public function getSiteListQuery()
{
  $this->db->select(array("tb_aktual.*", "tb_site_list.*"));
  $this->db->from("tb_aktual");
  $this->db->join("tb_site_list", "tb_site_list.site_id_po = tb_aktual.site_id_actual");
}

public function getSiteList()
{
  $this->getSiteListQuery();
  $order = array(null, "tb_aktual.wid", "tb_aktual.site_id_actual", "tb_site_list.site_name");
  if(isset($_POST["order"])){
    $this->db->order_by($order[$_POST["order"]["0"]["column"]], $_POST["order"]["0"]["dir"]);
  }
  else {
    $this->db->order_by("tb_aktual.site_id_actual", "ASC");
  }
  if($_POST["length"] != -1){
    $this->db->limit($_POST['length'], $_POST['start']);
  }
  if(isset($_POST["search"]["value"]))
  {
    $this->db->where("
      tb_aktual.wid LIKE '".$_POST["search"]["value"]."%' OR
      tb_aktual.site_id_actual LIKE '".$_POST["search"]["value"]."%' OR
      tb_site_list.site_name LIKE '".$_POST["search"]["value"]."%'
    ");
  }
  $query = $this->db->get();
  return $query->result();
}

public function getSiteListFilteredData()
{
  $this->getSiteListQuery();
  if(isset($_POST["search"]["value"]))
  {
    $this->db->where("
      tb_aktual.wid LIKE '".$_POST["search"]["value"]."%' OR
      tb_aktual.site_id_actual LIKE '".$_POST["search"]["value"]."%' OR
      tb_site_list.site_name LIKE '".$_POST["search"]["value"]."%'
    ");
  }
  $query = $this->db->get();
  return $query->num_rows();
}

public function getSiteListNumRows()
{
  $this->getSiteListQuery();
  $query = $this->db->get();
  return $query->num_rows();
}

Any ideas?
Thanks


How to change PDF export data borders?

$
0
0

Hi,

When I export data on click print button it generates pdf with very light gray color borders I wants to change that to black, please give me a solution.

Thank you in advance.

Enlarge Image on Hovering

$
0
0

I am having a field in ajax datatable in which Images are shown. What I want to achieve is enlarge the image on hovering to that particular image. Any way to do so coz I am using this datatable in erpnext and can write code in js or I had to overwrite the hmtl via jquery/javascript. Any suggestions will be appreciated.

Thank You...!!

PDF Export Text and Print Button

DataTables warning: table id=student_info - Cannot reinitialise DataTable why?

$
0
0
<script>
    $(document).ready(function () {
        // Setup - add a text input to each footer cell
        $('#student_info thead tr').clone(true).appendTo('#student_info thead');
        $('#student_info thead tr:eq(1) th').not(":eq(5)").each(function (i) {
            var title = $(this).text();
            $(this).html('<input class="form-control" type="text" placeholder="Search ' + title + '" />');
            var table = $('#student_info').DataTable({
                dom: 'Blfrtip',
                buttons: [
                    'copy', 'csv', 'excel', 'pdf', 'print'
                ],
                lengthMenu: [[20, 50, 100, -1], [20, 50, 100, "All"]]
            });
            // Apply the search
            table.columns().eq(0).each(function (i) {
                if (i == 5)
                    return; //Do not add event handlers for these columns
                $('input', table.column(i).header()).on('keyup change', function () {
                    table
                            .column(i)
                            .search(this.value)
                            .draw();
                });
            });
            table.column(3).every(function () {
                var column = this;
                var select = $('<select class="form-control"><option value="">Select One</option></select>')
                        .appendTo($(column.header()).empty())
                        .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) {
                    if (d) {
                        select.append('<option value="' + d + '">' + d + '</option>')
                    }
                });
            });
            table.column(4).every(function () {
                var column = this;
                var select = $('<select class="form-control"><option value="">Select One</option></select>')
                        .appendTo($(column.header()).empty())
                        .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) {
                    if (d) {
                        select.append('<option value="' + d + '">' + d + '</option>')
                    }
                });
            });
        });
    });
</script>

how to add a row dramatically on a button click event from a modal form

$
0
0

hi, everyone, I'm very new to datatables and need help I'm trying to add a new row to a datatable using a modal form it adds a blank row and in the type column witch is populate with a select html object I get thie [object HTMLSelectElement]

this is the code

($(document).ready(function(){
var parttb = $('#tbparts').DataTable();
var partnum = $('#partnumber').val();
var partdescr = $('#partname').val();
var parttype = $('#partty').val();
var partqty = $('#Quantity').val();
var partprice = $('#Price').val();

    $('#add').on('click', function(){
        parttb.row.add( [
                partnum,
                partdescr,
                partty,
                partqty,
                partprice
              ]).draw(false);
    });


});)
Viewing all 81395 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>