How to apply a zip code mask to a datatable column using Javascript?

Asked

Viewed 1,192 times

1

I have a Datatable in my View Index that has the CEP column that needs to have a CEP mask (ex: 29780-000). Does anyone know how to do this using Javascript?

<table class="table table-hover table-bordered dataTable table-striped width-full center-header table-responsive" id="dtPrincipal">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.CepId)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Endereco)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Complemento)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Bairro)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Cidade)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.UF)
                    </th>
                    @*<th>
                        @Html.DisplayNameFor(model => model.PadraoSistema)
                    </th>*@
                    <th>
                        @Html.DisplayName("Ações")
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.CepId)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Endereco)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Complemento)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Bairro)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Cidade)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.UF)
                    </td>
                    @*<td>
                        @Html.DisplayFor(modelItem => item.PadraoSistema)
                    </td>*@
                    <td>
                        <a title="Editar" asp-action="Edit" asp-route-id="@item.CepId" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row">
                            <span class="icon-2x wb-edit"></span>
                        </a>
                        <a title="Detalhes" asp-action="Details" asp-route-id="@item.CepId" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row">
                            <span class="icon-2x wb-search"></span>
                        </a>
                        <a title="Excluir" asp-action="Delete" asp-route-id="@item.CepId" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row">
                            <span class="icon-2x wb-trash"></span>
                        </a>
                        <a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-id="@item.CepId" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico">
                            <span class="icon-2x wb-time"></span>
                        </a>
                    </td>
                </tr>
                }
            </tbody>
        </table>

<script type="text/javascript">


        $('#dtPrincipal').DataTable({
            "columnDefs": [
                { className: "align-center", "targets": [5,6] },
                { className: "align-right", "targets": [0] }
            ],
            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",
                "searchPlaceholder": "Pesquise qualquer coisa",               
                "oPaginate": {
                    "sNext": "Próximo",
                    "sPrevious": "Anterior",
                    "sFirst": "Primeiro",
                    "sLast": "Último"
                },
                "oAria": {
                    "sSortAscending": ": Ordenar colunas de forma ascendente",
                    "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }
        });

inserir a descrição da imagem aqui

2 answers

2


Use the settings columnDefs, inform which column you want to format by targets and in render receives a formatting function that can be applied, example:

"render": function(data, type, row) {
    return data.substring(0, 5) + "-" + data.substring(5);
}

Complete minimum example:

$(document).ready(function() {
  $('#example').DataTable({
    "columnDefs": [{
      "targets": [0],
      "visible": true,
      "searchable": false,
      "render": function(data, type, row) {
        return data.substring(0, 5) + "-" + data.substring(5);
      },
    }]
  });
});
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>

<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>CEP</th>
      <th>UF</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>01001000</td>
      <td>SP</td>
    </tr>
    <tr>
      <td>29780000</td>
      <td>SP</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th>CEP</th>
      <th>UF</th>
    </tr>
  </tfoot>
</table>

Reference: Datatable - Column Rendering

  • 1

    Thanks for the help @Virgilio Novic. It worked 100%!

1

Another alternative is to bring your ZIP code already formatted in the Model

Model:

    public string CEP { get; set; }
    public string CepFormatado { get {
            if(CEP != null)
                return Convert.ToUInt64(CEP).ToString(@"00000\-000");
            return string.Empty;
        }
    }

View:

<table class="table table-hover table-bordered dataTable table-striped width-full center-header table-responsive" id="dtPrincipal">
            <thead>
                <tr>
                    <th>
                        @Html.DisplayNameFor(model => model.CepId)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Endereco)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Complemento)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Bairro)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.Cidade)
                    </th>
                    <th>
                        @Html.DisplayNameFor(model => model.UF)
                    </th>
                    @*<th>
                        @Html.DisplayNameFor(model => model.PadraoSistema)
                    </th>*@
                    <th>
                        @Html.DisplayName("Ações")
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.CepFormatado)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Endereco)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Complemento)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Bairro)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Cidade)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.UF)
                    </td>
                    @*<td>
                        @Html.DisplayFor(modelItem => item.PadraoSistema)
                    </td>*@
                    <td>
                        <a title="Editar" asp-action="Edit" asp-route-id="@item.CepId" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default edit-row">
                            <span class="icon-2x wb-edit"></span>
                        </a>
                        <a title="Detalhes" asp-action="Details" asp-route-id="@item.CepId" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default footable-row-detail-row">
                            <span class="icon-2x wb-search"></span>
                        </a>
                        <a title="Excluir" asp-action="Delete" asp-route-id="@item.CepId" data-modal="" class="btn btn-sm btn-icon btn-pure btn-default on-default remove-row">
                            <span class="icon-2x wb-trash"></span>
                        </a>
                        <a title="Histórico" class="btn btn-sm btn-icon btn-pure btn-default on-default clockpicker" data-id="@item.CepId" data-toggle="modal" data-target="#pessoaHistory" data-original-title="Histórico">
                            <span class="icon-2x wb-time"></span>
                        </a>
                    </td>
                </tr>
                }
            </tbody>
        </table>
  • Great suggestion @Netinho Santos! Thanks a lot for the help! I decided to use the suggestion of friend Virgilio, because it is the closest to what I need. I think your suggestion will be useful in a part of my project that I haven’t gotten there yet.

Browser other questions tagged

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