Use a Focus for several fields.

Asked

Viewed 176 times

0

Good morning, I created a function to validate cnpj in my form and I need to use a Focus() for the cursor to be in the input when the user enters the wrong cnpj, but there are 3 distinct fields of cnpj. I’ve done it many ways, but he only accepts in the first field.

jquery:

jQuery.fn.validacnpj = function () {
this.change(function () {
    CNPJ = $(this).val();
    if (!CNPJ) {
        return false;
    }
    erro = new String;
    if (CNPJ == "00.000.000/0000-00") {
        erro += "CNPJ inválido\n\n";
    }
    CNPJ = CNPJ.replace(".", "");
    CNPJ = CNPJ.replace(".", "");
    CNPJ = CNPJ.replace("-", "");
    CNPJ = CNPJ.replace("/", "");

    var a = [];
    var b = new Number;
    var c = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];
    for (i = 0; i < 12; i++) {
        a[i] = CNPJ.charAt(i);
        b += a[i] * c[i + 1];
    }
    if ((x = b % 11) < 2) {
        a[12] = 0
    } else {
        a[12] = 11 - x
    }
    b = 0;
    for (y = 0; y < 13; y++) {
        b += (a[y] * c[y]);
    }
    if ((x = b % 11) < 2) {
        a[13] = 0;
    } else {
        a[13] = 11 - x;
    }
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])) {
        erro += "Dígito verificador com problema!";
    }
    if (erro.length > 0) {
        $(this).val('');
        alert(erro);
        $(document).ready(function () {
            $("#cnpj").focus();
        });

        setTimeout(function () {
            $(this).focus()
        }, 100);
    }
    return $(this);
});

};

index:

<head>
    <meta charset="ISO-8859-1">
    <title>Formulário de Cadastro</title>
    <link rel="stylesheet" type="text/css" href="css/style.css"> 
    <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="js/jquery-validacpfecnpj.js"></script>

    <script type="text/javascript" src="js/jquery.maskedinput.min.js"></script>
    <script type="text/javascript" src="js/util.js"></script>
</head>
<body>
    <div class="container" style="margin: 0 auto; width: 1230px; margin-top: -8px  ">
        <div class="logo">
            <img alt="Logo Prefeitura" src="img/bg_header_logo.png" >
        </div>

        <form action="processaCadastro.php" method="post" name="formCadastro" id="formCadastro">
            <fieldset>
                <legend>Dados do Condomínio</legend>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label class="lblCondominio">Nome do condomínio ou edifício:</label>
                        <label class="lblFieldAlert">*</label>
                    </div>
                    <div class="itemInputForm4">
                        <input type="text" name="nomeCondominio" placeholder="condomínio/edifício" required>
                    </div>
                </div>

                <div class="groupItemForm">
                    <label>Possue CNPJ?</label>
                    <input type="radio" name="checkCNPJ" id="checkCNPJ" value="nao" /><label>Não</label>
                    <input type="radio" name="checkCNPJ" id="checkCNPJ" value="sim" checked="checked" /><label>Sim</label>
                    <input type="text" name="cnpj" class="cnpj" id="cnpj" placeholder="xx.xxx.xxx/xxxx-xx"  />
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>Telefone:</label>
                    </div>
                    <div class="itemInputForm1">
                        <input type="tel" class="fixo" name="telCondominio" placeholder="(xx) xxxx-xxxx">
                    </div>
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>Celular:</label>
                    </div>
                    <div class="itemInputForm1">
                        <input type="tel" class="cell" name="celCondominio" placeholder="(xx) xxxxx-xxxx">
                    </div>
                </div>

            </fieldset>

            <fieldset>
                <legend>Dados do Síndico</legend>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>Nome do Síndico:</label><label class="lblFieldAlert">*</label>
                    </div>
                    <div class="itemInputForm3">
                        <input type="text" name="nomeSindico" required >
                    </div>
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>CPF do Síndico:</label><label class="lblFieldAlert">*</label>
                    </div>
                    <div class="itemInputForm1">
                        <input type="text" id="cpf" class="cpf" name="cpfSindico" required >
                    </div>
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>E-mail:</label><label class="lblFieldAlert">*</label>
                    </div>
                    <div class="itemInputForm3">
                        <input type="email" name="email" id="email" required >
                    </div>
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>Confirmação de E-mail:</label><label class="lblFieldAlert">*</label>
                    </div>
                    <div class="itemInputForm3">
                        <input type="email" name="emailConfirm" id="emailConfirm" required >
                    </div>
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>Telefone:</label>
                    </div>
                    <div class="itemInputForm1">
                        <input type="text" class="fixo" name="telSindico" placeholder="(xx) xxxx-xxxx">
                    </div>
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>Celular 1:</label><label class="lblFieldAlert">*</label>
                    </div>
                    <div class="itemInputForm1">
                        <input type="tel" class="cell" name="cel1Sindico" placeholder="(xx) xxxxx-xxxx" required>
                    </div>
                </div>

                <div class="groupItemForm">
                    <div class="itemForm">
                        <label>Celular 2:</label>
                    </div>
                    <div class="itemInputForm1">
                        <input type="tel" class="cell" name="cel2Sindico" placeholder="(xx) xxxxx-xxxx">
                    </div>
                </div>

            </fieldset>

            <fieldset>
                <legend>Outras Informações</legend>

                <div class="groupItemForm">
                    <label>Tem administradora de condomínio contratada?</label>
                    <input type="radio" name="admCondominio" value="nao" required><label>Não</label>
                    <input type="radio" name="admCondominio" value="sim" checked="checked" required><label>Sim</label>
                    <div class="itemInputDoubleForm1">
                        <input type="text" name="empr_adm" class="empr_adm" id="empr_adm" placeholder="Nome da administradora" />
                        <label>CNPJ</label>
                        <input type="text" name="cnpj_adm" class="cnpj" id="cnpjadmin" placeholder="xx.xxx.xxx/xxxx-xx"  />
                    </div>
                </div>

                <div class="groupItemForm">
                    <label>Tem empresa de manutenção de elevadores contratada?</label>
                    <input type="radio" name="manutancaoElevador" value="nao" required><label>Não</label>
                    <input type="radio" name="manutancaoElevador" value="sim" checked="checked" required><label>Sim</label>
                    <div class="itemInputDoubleForm2">
                        <input type="text" name="empr_manut" class="empr_manut" id="empr_manut" placeholder="Nome da empresa" />
                        <label>CNPJ</label>
                        <input type="text" name="cnpj_manut" class="cnpj" id="cnpjmanut" placeholder="xx.xxx.xxx/xxxx-xx"  />
                    </div>
                </div>

                <div class="groupItemForm">
                    <label>Há interesse em participar de palestra abordando as obrigações tributárias?</label>
                    <input type="radio" name="participacacao" value="nao" ><label>Não</label>
                    <input type="radio" name="participacacao" value="sim" checked="checked" ><label>Sim</label><br><br>
                    <div class="itemInputCheckboxForm">
                        <div class="itemForm">
                            <label>Período desejado para participar da palestra:</label>
                        </div>
                        <input type="checkbox" name="turnoPalestraManha" value="Sim" ><label>Manhã</label><br>
                        <input type="checkbox" name="turnoPalestraTarde" value="Sim" ><label>Tarde</label><br>
                        <input type="checkbox" name="turnoPalestraNoite" value="Sim" ><label>Noite</label><br>

                        <div class="groupItemForm">
                            <div class="itemForm">
                                <label>Número de interessados:</label>
                                <input type="number" name="numeroDeParticipantes" placeholder="Nº Interessados" min="1" ><br><br>
                                <label class="lblFieldAlert"><b>AVISO! Em breve será enviado via e-mail o calendário de palestras para reserva de vagas.</b></label>
                            </div>
                        </div>
                    </div>
                </div>
            </fieldset>
            <br>
            <label>Códgio</label><br>

            <img src="/common/rotinas_php/Gerajpeg/Gerajpeg.php"><br>
            <input type=text id="letras" name="letras" required size="4" maxlength="5">
            <br><br>

            <input type="submit" value="Enviar">

            <div class="groupItemForm">

            </div>
        </form>

        <footer style="margin-bottom: 30px">
            <hr style="margin-top: 30px">  
            <div class="img_prefeitura" style="float:left">
                <img src="img/logo_portalfinancas.png">
            </div>

            <div class="footer_dados" style="float: right; font-family: Arial;">
                <div style="color: darkblue; font-size: 20px; font-weight: bold"> Secretaria de Finaças </div>
                <div style="color: darkblue">Cais do Apolo, 14º andar, Bairro do Recife</div>
                <div style="color: darkblue">Recife-PE, CEP 50030-903</div>
                <div style="color: darkblue; margin-top: 10px">Teleatendimento: (81) 3355-8261</div>
            </div>
        </footer>

    </div>
</body>

  • 1

    The identifier id should be unique on each page if you change the id then you can give the focus() wherever you want...

  • I’ve tried it this way, but it didn’t take

1 answer

1

Some remarks about your code:

  • Using Document.ready in incorrect location: this will not run within your code block:

    if (erro.length > 0) {
        $(this).val('');
        alert(erro);
        $(document).ready(function () {
            $("#cnpj").focus();
        });    // resto do código omitido
    

The "ready" event is from Document and will not be impacted by your if.

  • Two Focus: you’re using one first $("#cnpj").focus();, that will clearly position the Focus in the element with id "cnpj", regardless of who is wrong, the correct one, since you are validating the input itself would be $(this).focus() only.

  • Scope of the this: each Function has its own brush, and probably the this within the Function with setTimeout it’s not the same, so this does not mean the same object. Try to associate the this to a variable, thus:

    alert(erro);
    var elem = $(this);
    setTimeout(function () { elem.focus(); }, 100); 
    

I believe this will solve your problem.

Browser other questions tagged

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