CNPJ Mask function for field with dynamic value

Asked

Viewed 315 times

2

I’m having a question on the following occasion, I have a maskCNPJ function where the function obviously adds a mask on the supplier’s CNPJ number. The problem that is happening, comes from the fact that the function only works in the first CNPJ that comes when loading the page, since, when I select another supplier, is bring your CNPJ and your ID, so the CNPJ field does not get the mask. Can anyone tell me how to make the mask follow the CNPJ number, even when changing supplier ?

index php.:

<?php
error_reporting(0);
header('Content-Type: text/html; charset=utf-8');

$servidor = 'localhost';
$usuario = 'root';
$senha = '';
$dbname = 'testevip';

$connect = mysqli_connect($servidor, $usuario, $senha, $dbname);

# Fornecedores
$query_fornecedores = "SELECT nome FROM fornecedores ORDER BY nome ASC LIMIT 20";
$result1 = mysqli_fetch_all(mysqli_query($connect, $query_fornecedores), MYSQLI_ASSOC);

# Produtos
$query_produtos = "SELECT * FROM produto ORDER BY desc_produto ASC";
$result2 = mysqli_fetch_all(mysqli_query($connect, $query_produtos), MYSQLI_ASSOC);

mysqli_close($connect);
?>

<!doctype html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <!-- Essas duas linhas são do Bootstrap, deixa a formatação mais 'bonita' -->
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.min.css"/>
    <link rel="stylesheet" href="css/style.css">
    <title>Testando API</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<!--<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.min.js"></script>-->
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/jquery.mask.js"></script>
<script src="js/bootstrap-select.js"></script>
<script src="js/script.js"></script>


<body onload="dataAtual()">

<div class="container-fluid">
    <div class="container" id="cabecalho">
        <br>
        <header class="cabecalho">
            <div class="wrap">
                <div class="imagem-header">
                    <img src="imagens/logo_ip.png" alt="Logo Varejão Irmaãos Patrocinio">
                    <h1>Vales - Varejão Irmãos Patrocinio</h1>
                </div>
                <div class="dados-header">
                    <div id="id-pedido"></div>
                    <div id="data-atual"></div>
                </div>

            </div>
        </header>
    </div>

    <div class="container" id="fornecedores">

        <div class="title-padrao">
            <h1 class="text-center">Fornecedores</h1>
        </div>

        <div class="fornecedores-wrap">
            <div class="col-xs-1 col-sm-1 col-md-1 col-lg-1 select_height text-center">
                <b>ID:</b>
                <div id="fornecedor-id" class="font-pop"></div>
            </div>

            <div class="col-xs-5 col-sm-5 col-md-5 col-lg-8 select_height" id="div_fornecedores">
                <!-- selectpicker é o elemento que coloca o input e o select juntos -->

                <b>Fornecedor:</b>
                <select class="selectpicker form-control" data-show-subtext="false" data-live-search="true"
                        name="select_fornecedor<?=$id?>" id="select_fornecedor<?=$id?>" onchange="initFornecedores(<?=$id?>)">
                    <?php
                    foreach ($result1 as $item_fornecedores) {
                        echo '<option data-subtext="' . $item_fornecedores['nome'] . '" value="'
                            . $item_fornecedores['nome'] . '">' . $item_fornecedores['nome'] . '</option>';
                    }
                    ?>
                </select>
            </div>
            <div class="col-xs-5 col-sm-5 col-md-5 col-lg-3 text-center select_height">
                <b>CNPJ:</b>
                <div name="cnpj" class="font-pop" id="cnpj"></div>
            </div>
        </div>
    </div>
   </div>
</body>
<script>
    dataAtual();
    initFornecedores();
    initProdutos();
    initPedido();
</script>
</html>

Jquery/ AJAX functions:

function mask() {
    $('#cnpj').mask('99.999.999/9999-99');
}

function initFornecedores(){
    var letras_fornecedores = document.getElementById("select_fornecedor").value;
    var $cnpj = $('#cnpj');
    $.ajax({
        type: "GET",
        url: "API.php",
        data: {
            "mode": "fornecedores",
            "letras_fornecedores": letras_fornecedores,
        },
        dataType:"JSON",
        //CASO DÊ TUDO CERTO
        success:function(data){         
            console.log(data);
            document.getElementById('fornecedor-id').innerHTML = data[0]['id_fornecedor'];
            $($cnpj).text(data[0]['cpf_or_cnpj']);
            mask();
        },
        error:function(request, error)
        {
            // console.log("Request: " + JSON.stringify(request));
        }
    });
}

1 answer

2


Use the method .unmask() before applying the mask again:

$cnpj.unmask().text(data[0]['cpf_or_cnpj']);

Note that I changed $($cnpj) by just $cnpj because the variable $cnpj is already the jQuery object element. Therefore it is not necessary put inside $().

Plugin Documentation

  • Thank you very much Sam, I took the test and it worked perfectly !

Browser other questions tagged

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