Create mask for text

Asked

Viewed 207 times

0

I need to return a CNPJ value with a mask via Javascript to a text in a td tag of my html code. The value is returned from the standard CNPJ formatted bd as in the code below:

<tr th:each="cliente : ${clientes}" class="cliente">
<td id="#cnpj" th:text="${cliente.cnpj}" class="cnpjTd"></td>
<td id="#razaosocial" th:text="${cliente.razaoSocial}"></td>

For example: the cnpj client returns a "11111111111111" and accurate value that is formatted as "11.111.111/1111-11".

How can I do that?

  • Related: https://answall.com/questions/77505/formatar-mascara-para-cnpj , https://answall.com/questions/177760/como-se-faz-máscara-para-display-de-fone-cnpj-cpf-etc-nolaravel, https://answall.com/questions/94956/máscara-para-cpf-e-cnpj-no-mesmo-campo

1 answer

0


I have a code here that I always use and saves me a lot. Follow it below, just you call the function with the value you want.

  $(document).ready(function(){
    $("#mascarar").click(function(){
      $("#depois").html(Mascara($('#antes').html()));
    });
  });
  function Mascara(valorFormatar) {
    //Coloca ponto entre o segundo e o terceiro dígitos
    valorFormatar=valorFormatar.replace(/^(\d{2})(\d)/,"$1.$2")

    //Coloca ponto entre o quinto e o sexto dígitos
    valorFormatar=valorFormatar.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")

    //Coloca uma barra entre o oitavo e o nono dígitos
    valorFormatar=valorFormatar.replace(/\.(\d{3})(\d)/,".$1/$2")

    //Coloca um hífen depois do bloco de quatro dígitos
    valorFormatar=valorFormatar.replace(/(\d{4})(\d)/,"$1-$2")

    return valorFormatar;
  }
<!DOCTYPE html>
<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>

  <h2>Dado antes</h2>

  <p id="antes">09673442000173</p>

  <h2>Dado depois</h2>

  <p id="depois"></p>

  <button type="button" id="mascarar">Formatar!</button>
  </body>
</html>

Browser other questions tagged

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