Define attributes in columns <td> in html table, with javascript

Asked

Viewed 460 times

0

I have the following code below that receives some data via ajax and assigns the received values in a table that is defined with the "Datatable".

I’d like to know how I set attribute to my "td" tags (which are created dynamically) id, name and events like onclick.

All rows that are created must have Ester attributes.

function processed(p_campanha_id, p_pagina){
        var table =  $('#example').DataTable();
        table.fnClearTable();           

        var campanha_id = p_campanha_id;                      
        if(!p_pagina){
          pagina = 1;
        }    

        var pagina = p_pagina;      

        $.ajax({
          dataType: 'json',
          url: "<?php echo LINK_DEFAULT; ?>campanhas/estatisticaprocessed",
          data: { campanha_id : campanha_id, pagina: pagina },
          complete: function(result) {
            console.log(result);

            var json = JSON.parse(result.responseText);
            var val_data;

            $.each(json.detalheProcessed, function(i, val){   
              val_data = convert(val.event_timestamp); 

              dadosTabela = [val.email, 'Enviado', '', val_data ];

              table.fnAddData(dadosTabela);                    
              table.addClass('center hidden-xs');
            });
            table.fnDraw();
            dataCerta(); 

          }
        });
    }








<table class="table table-striped table-bordered table-hover" id="example" name="example" onBlur="dataCerta();" onclick = "dataCerta(); " onfocus="dataCerta();">
                                    <thead onBlur="dataCerta();" onclick = "dataCerta(); " onfocus="dataCerta()";>
                                        <tr>
                                            <!-- <th class="center">Template Utilizado</th> -->
                                            <th class="center hidden-xs" onBlur="dataCerta();" onclick = "dataCerta();">Email </th>
                                            <th class="center hidden-xs" onBlur="dataCerta();" onclick = "dataCerta(); " onfocus="dataCerta();">Evento</th>
                    <th class="center hidden-xs" onBlur="dataCerta();" onclick = "dataCerta(); " onfocus="dataCerta();">Motivo</th>
                    <th class="center hidden-xs" onBlur="dataCerta();" onclick = "dataCerta(); " onfocus="dataCerta();" style="width: 150px;">Data do Evento</th>

</tr>

            <tbody>


                    <tr>

                      <td class="center"></td>
                      <td class="center"></td>
                      <td class="center"></td>
                      <td class="center"></td>

                </tr>                                           
            </tbody>

            </table>

Resultado da tabela montada

This is the code that does the query in the database and returns the json:

    public function estatisticaopensAction(){

    set_time_limit(240);
    ini_set('memory_limit','1024M');
    ini_set('max_input_time', 300);
    if($this->_getParam('campanha_id')) {

      $sessao = new Zend_Session_Namespace(SESSION_MOBCLI);
      $empresa_id = $sessao->id;
      $campanha_id = $this->_getParam('campanha_id');
      $modelCampanha = new Application_Model_DbTable_Campanhasmobile();
      $page = $this->_getParam('pagina', 1);
      $qnt_res_pagina = 50;
      $inicio = ($qnt_res_pagina * $page) - $qnt_res_pagina;

      $sql = "SELECT *
              FROM estatisticas_enviado
              WHERE empresa_id = $empresa_id AND campanha_id = $campanha_id AND event = 'open' LIMIT $inicio, $qnt_res_pagina";

      $db = Zend_Db_Table::getDefaultAdapter();
      $stmt = $db->query($sql);
      $result = $stmt->fetchAll();


      $sql_total_ee = "SELECT COUNT(estatisticas_id) as total_opens
              FROM estatisticas_enviado
              WHERE empresa_id = $empresa_id AND campanha_id = $campanha_id AND event = 'open'";

      $stmt_total_ee = $db->query($sql_total_ee);
      $result_total_ee = $stmt_total_ee->fetchAll();  
      $total_opens = $result_total_ee[0]['total_opens'];


      //Paginacao--------------------------------------------
      $qnt_paginas = ceil($total_opens / $qnt_res_pagina);

      $max_links = 8;

      $pg_links = array();

      $cnt = 0;
      for($pag_ant = $page - $max_links; $pag_ant <= $page - 1; $pag_ant++){
        $cnt = $cnt+1;
        if($pag_ant >= 1){
          $pg_links[$cnt] = $pag_ant;
        }
      }

      $cnt2 = 0;
      for($pag_dep = $page; $pag_dep <= $page + 1; $pag_dep++){
        $cnt2 = $cnt2+1;
        if($pag_dep <= $qnt_paginas){
          $pg_links[$cnt2] = $pag_dep;
        }

      }

      sort($pg_links);

      $primeira_pagina = ['prim_pagina'=>'Primeira', 'n_pagina'=>1];
      $ultima_pagina = ['ult_pagina'=>'Ultima', 'n_pagina'=>$qnt_paginas];        


      $detalheOpens= $result; 

      echo json_encode(array('primeira_pagina'=>$primeira_pagina, 'ultima_pagina'=>$ultima_pagina, 'pg_links'=>$pg_links, 'detalheOpens' => $detalheOpens)); exit;


    }else{
      $this->_redirect(LINK_DEFAULT . 'campanhas');
    }


  }

This is the result return: inserir a descrição da imagem aqui

At the moment I just make use of the fields, email and event_timestamp to create my table.

  • You can give an example of what this result has?

  • I will edit and put a print of the table, but the return is just a select I do in a table and step by a json.

  • JSON interests me because I can make an example that works

  • I edited the post by entering my controller code. Help?

  • The cool thing would be to put a way out, as @Sergio asked.

  • I made another issue in the post to show the return of my query.

  • Can you put this JSON in text (anonymizing these emails)? at least one array with 1 object to use... I don’t have time to write by hand even though I really wanted to help...

  • Always when you put examples, use text, not images.

  • Sorry, I will pay attention to the next posts. I am very grateful for your help!

  • It was very well exemplified at the bottom @Taffarelxavier. Thank you very much!

  • 1

    On time, we are here to help, always in our limitations.

Show 6 more comments

1 answer

1


Based on official documentation common date. and on this topic How to add attribute in TR and TD? and createdRow

[Inspect the table below when executing the code, and you will see that the attributes have been added to the 'TD' tags']

The secret is here:

 'createdRow': function(row, data, dataIndex) {
      $(row).find('td').attr({
        'id': 1
      });
      $(row).find('td').attr({
        'name': 1
      });
      $(row).find('td').attr({
        'onclick': 1
      });
      //ADICIONA QUANTOS ATRIBUTOS VOCÊ QUISER.
    }

Instead of doing this:

   $.each(json.detalheProcessed, function(i, val){   
              val_data = convert(val.event_timestamp); 

              dadosTabela = [val.email, 'Enviado', '', val_data ];

              table.fnAddData(dadosTabela);                    
              table.addClass('center hidden-xs');
            });
            table.fnDraw();
            dataCerta(); 

          }

Try this:

Note that you will have to make some changes as your data.

 $('#example').dataTable({
    data: json.detalheProcessed,
    "columns": [
      //SUAS COLUNAS DO SEU JSON AQUI COMO OBJETOS: IDÊNTICAS AS COLUNAS
    ],
    'createdRow': function(row, data, dataIndex) {
      $(row).find('td').attr({
        'id': 1
      });
      $(row).find('td').attr({
        'name': 1
      });
      $(row).find('td').attr({
        'onclick': 1
      });
    }

Complete Code of a Minimum Example:

//Seus dados: Você pode alterar as chaves aqui, mas
//deverá alterar também abaixo, na chave 'columns'
var dadosTabela = [{
    company_id: "1",
    email: "[email protected]"
  },
  {
    company_id: "2",
    email: "[email protected]"
  }
]

$(document).ready(function() {

  $('#example').dataTable({
    data: dadosTabela,
    "columns": [{
        "data": "company_id"
      },
      {
        "data": "email"
      }

    ],
    'createdRow': function(row, data, dataIndex) {
      console.log(data);
      //NOTE ISTO AQUI: console.log(data); IMPORTANTE PARA
      //NÃO DEIXAR OS DADOS CONSTANTES, COMO ESTÃO ABAIXO.
      /*Meu array:
{
  "company_id": "1",
  "email": "[email protected]"
}
{
  "company_id": "2",
  "email": "[email protected]"
}
      */
      $(row).find('td').attr({
        'id': 1
      });
      $(row).find('td').attr({
        'name': 1
      });
      $(row).find('td').attr({
        'onclick': 1
      });
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">

<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>

<table id="example" class="display">
  <thead>
    <tr>
      <th>COMPANY_ID</th>
      <th>EMAIL</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

  • Thanks, very good! Helped too!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.