Create javascript-mounted title attribute in <td>

Asked

Viewed 229 times

5

I have a table called gridContudo. In this table, there is this <td>: { width: 100, name: 'OBSERVACAO', index: 'OBSERVACAO', label: 'Observação'}]. What I need is to create a title attribute in this< td>. How do I do? If I put this: title: 'meu_title', it just doesn’t work. I’ve sinned this, but I haven’t understood it all:

$('#gridConteudo tr td:nth-child(15)').each(function (i) {
    if (i > 0) { //skip header
        var sContent = $(this).text();
        $(this).attr("title", $(this).html());
        //if (sContent.length > 20) {
        //    $(this).text(sContent.substring(0, 20) + '...');
        //}
    }
});

I don’t quite understand that line:

tr td:nth-child(15)')

As the content of <td>is very big, I put this line but it didn’t work:

if (sContent.length > 20) {
   $(this).text(sContent.substring(0, 20) + '...');

As I’m having trouble making it work, as a whole, I think it didn’t work because of these problems. Didn’t work it didn’t show more than 20 lines.

Below my function that mounts the table. The examples I downloaded, they work in a table made by pure html, but when I apply in the table below, it doesn’t work, nothing at all.

function CarregarGrid() {
            $('#gridConteudo').jqGrid({
                colModel: [{ width: 80, name: 'COD_OPERADORA', index: 'COD_OPERADORA', label: 'Operadora', formatter: GridOperadoraFormatter },
                           { name: 'NOM_OPERADORA', index: 'NOM_OPERADORA', hidden: true },
                           { width: 80, name: 'SITUACAO', index: 'SITUACAO', label: 'Situação' },
                           { width: 90, name: 'DT_EXCLUSAO_OPERADORA', index: 'DT_EXCLUSAO_OPERADORA', label: 'Dt. Exclusão Operadora', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 130, name: 'COD_REDE', index: 'COD_REDE', label: 'Rede', formatter: GridRedeFormatter },
                           { name: 'NOM_REDE', index: 'NOM_REDE', hidden: true },
                           { width: 90, name: 'DT_EXCLUSAO_REDE', index: 'DT_EXCLUSAO_REDE', label: 'Dt. Exclusão Rede' },
                           { width: 120, name: 'COD_PRESTADOR_SUBSTITUTO', index: 'COD_PRESTADOR_SUBSTITUTO', label: 'Prestador Substituto', formatter: GridPrestadorSubstitutoFormatter },
                           { name: 'NOME_PRESTADOR_SUBSTITUTO', index: 'NOME_PRESTADOR_SUBSTITUTO', hidden: true },
                           { width: 115, name: 'DESC_MOTIVO_EXCLUSAO', index: 'DESC_MOTIVO_EXCLUSAO', label: 'Motivo Exclusão' },
                           { width: 95, name: 'DT_NOTIF_VOLUNTARIA', index: 'DT_NOTIF_VOLUNTARIA', label: 'Dt. Notificação Excl. Voluntária', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_LIMITE_ATD', index: 'DT_LIMITE_ATD', label: 'Dt. Limite Realização', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_LIMITE_REMESSA', index: 'DT_LIMITE_REMESSA', label: 'Dt. Limite Apresentação', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_LIMITE_RECURSO', index: 'DT_LIMITE_RECURSO', label: 'Dt. Limite Reapresentação', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 90, name: 'DT_FIM_EXIBE_DIRECIONAMENTO', index: 'DT_FIM_EXIBE_DIRECIONAMENTO', label: 'Dt. Fim Exibe Site', sorttype: 'date', formatter: 'date', formatoptions: { srcformat: "d/m/Y", newformat: 'd/m/Y' } },
                           { width: 100, name: 'OBSERVACAO', index: 'OBSERVACAO', label: 'Observação'}],
                url: urlControle + '/GetPrestadorOperadora',
                mtype: 'POST',
                postData: { "pEXEC": function () { return $("#pEXEC").val(); }, "pCodPrestadorTS": function () { return $("#hidCodPrestadorTS").val(); } },
                jsonReader: { repeatitems: false, root: function (obj) { return obj.Items; } },
                datatype: "json",
                autowidth: true,
                shrinkToFit: false,
                forceFit: true,
                loadonce: true,
                loadError: function (xhr, st, err) { $.notificacoes.erro("@TopSaudeResource.notificacao_erro_transacao"); },
                loadComplete: function () {

                    if ($('#hidCodPrestadorTS').val() != '') {

                        var linhas = $("#gridConteudo").getDataIDs();

                        if (linhas.length <= 0) {
                            $('#divConteudo').hide();
                            $.notificacoes.erro("Prestador não está excluído em nenhuma Operadora e/ou Rede");
                        }
                        else {
                            $('#divConteudo').removeAttr('style');
                            $('#divConteudo').show();
                        }

                        $('table tbody tr td').each(function () {
                            var td = $(this);
                            var texto = td.text();
                            if (texto.length > 30) {
                                texto = texto.substr(0, 30) + '...';
                            }
                            td.attr('title', texto);
                        })
                    }
                }
            });

            $('#gridConteudo').jqGrid('setLabel', 'COD_OPERADORA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'SITUACAO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_EXCLUSAO_OPERADORA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'COD_REDE', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_EXCLUSAO_REDE', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'COD_PRESTADOR_SUBSTITUTO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DESC_MOTIVO_EXCLUSAO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_NOTIF_VOLUNTARIA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_LIMITE_ATD', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_LIMITE_REMESSA', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_LIMITE_RECURSO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'DT_FIM_EXIBE_DIRECIONAMENTO', '', { 'text-align': 'left' });
            $('#gridConteudo').jqGrid('setLabel', 'OBSERVACAO', '', { 'text-align': 'left' });
        }

The toottip should be in the column NOTE.

  • Have you taken a look at the Caption of this plugin ? http://www.guriddo.net/demo/bootstrap/functionality/custom_grid_caption/index.html

2 answers

2

I did not understand this line: 'tr td:Nth-Child(15)'

The selector Nth-Child() allows you to select the child element of a parent element, either by the index, by the child element class or by a formula.

In your case '#gridConteudo td:nth-child(15)' you are selecting the column at index 15 of your table.

As the content of the 'td' is very large, I put this line, but it did not work:

To limit the number of characters, your function is correct, I just created a function and am calling it in two moments, to change the table text and table title. You also do not need to check whether or not it is the first line, if you own the tbodyand thead in your table, just add in the function.

Obs.: You are using the function attr jQuery to change the attribute title, if you are using a recent version of jQuery, this function has been changed to prop.

See your refactored code:

$('#gridConteudo tbody td:nth-child(15)').each(function () {
    var sContent = $(this).text();
    //Alterar title
    $(this).attr("title", limitarCaracteres(sContent, 20));
    //Alterar coluna da tabela
    $(this).html(limitarCaracteres(sContent, 20));

    function limitarCaracteres(texto, qtde) {
        if (texto.length > qtde)
           texto = sContent.substring(0, qtde) + '...';
        return texto;
    });
});

2

What I need is to create a title attribute in this <td>. How I do?

You can do it like this:

$('table tbody tr td').each(function() {
  var td = $(this);
  var texto = td.text();
  td.attr('title', texto);
  if (texto.length > 30) {
    texto = texto.substr(0, 30) + '...';
  }
  td.text(texto);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table class="table text-center">
  <thead>
    <tr>
      <td>Descrição</td>
      <td>Valor</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Lorem Ipsum é simplesmente uma simulação de texto da indústria tipográfica e de impressos, e vem sendo utilizado desde o século XVI, quando um impressor desconhecido pegou uma bandeja de tipos e os embaralhou para fazer um livro de modelos de tipos.
        Lorem Ipsum sobreviveu não só a cinco séculos, como também ao salto para a editoração eletrônica, permanecendo essencialmente inalterado.</td>
      <td>R$10</td>
    </tr>
    <tr>
      <td>Café</td>
      <td>R$5</td>
    </tr>
  </tbody>
</table>

  • 1

    It is not the tooltip that should have 30 characters or 20, but what is being shown in <td>. The tooltip should show all content coming from the database.

  • @pnet now makes perfect sense for min, reissuing.

  • The tooltip didn’t work. In IE it shows and then disappears, what I want is a tooltip that while the mouse is on it, it doesn’t disappear. I tried several examples, it works in a common table, but in my table, which is mounted by javascript, it doesn’t work. I will post her full code and someone might help me. Let me explain. These examples I’ve been picking up on the internet, it even works on a common table, but with my table it doesn’t work.

  • @pnet understood, reedit your question by putting these details and your cross browsers tests that will help you get a better answer.

  • I made an edition and posted the code of the table, mounted by javascript.

Browser other questions tagged

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