Fill input with Function javascript result

Asked

Viewed 1,654 times

0

I am using the following function to validate CNPJ in Input:

function FormataCnpj(campo, teclapres) {
    var tecla = teclapres.keyCode;
    var vr = new String(campo.value);
    vr = vr.replace(".", "");
    vr = vr.replace("/", "");
    vr = vr.replace("-", "");
    tam = vr.length + 1;
    if (tecla != 14) {
        if (tam == 3)
            campo.value = vr.substr(0, 2) + '.';
        if (tam == 6)
            campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 5) + '.';
        if (tam == 10)
            campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/';
        if (tam == 15)
            campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/' + vr.substr(9, 4) + '-' + vr.substr(13, 2);
    }
}



function validarCNPJ(cnpj) {

    cnpj = cnpj.replace(/[^\d]+/g, '');

    if (cnpj == '') return false;

    if (cnpj.length != 14)
        return false;

    // Elimina CNPJs invalidos conhecidos
    if (cnpj == "00000000000000" ||
        cnpj == "11111111111111" ||
        cnpj == "22222222222222" ||
        cnpj == "33333333333333" ||
        cnpj == "44444444444444" ||
        cnpj == "55555555555555" ||
        cnpj == "66666666666666" ||
        cnpj == "77777777777777" ||
        cnpj == "88888888888888" ||
        cnpj == "99999999999999")
        return false;

    // Valida DVs
    tamanho = cnpj.length - 2
    numeros = cnpj.substring(0, tamanho);
    digitos = cnpj.substring(tamanho);
    soma = 0;
    pos = tamanho - 7;
    for (i = tamanho; i >= 1; i--) {
        soma += numeros.charAt(tamanho - i) * pos--;
        if (pos < 2)
            pos = 9;
    }
    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    if (resultado != digitos.charAt(0))
        return false;

    tamanho = tamanho + 1;
    numeros = cnpj.substring(0, tamanho);
    soma = 0;
    pos = tamanho - 7;
    for (i = tamanho; i >= 1; i--) {
        soma += numeros.charAt(tamanho - i) * pos--;
        if (pos < 2)
            pos = 9;
    }
    resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
    if (resultado != digitos.charAt(1))
        return false;


    return true;
}

calls her that way:

<input ID="txCNPJ_cad_emp" name="cnpj" class="form-control" placeholder="Digite o CNPJ" onkeyup="FormataCnpj(this,event)" onblur="if(!validarCNPJ(this.value)){alert('CNPJ Informado é inválido'); this.value='';}" required autofocus></>

If the CNPJ is invalid it returns an Alert to me, but instead of displaying an Alert I need it to change another input

<input ID="txCNPJ_cad_emp" name="cnpj">

putting the error message in it: "Invalid CNPJ".

  • @Daniel, the codes are the same, however, it does not have the answer that is like filling the Input with the Function result or Return in javascript and if the validation gives false fill the input with the validation error text

  • If that’s all, what’s so hard to do this.value = "CNPJ inválido";?

  • It remains duplicate. Just look at the solution proposed there, as Daniel commented and replied.

  • Okay, @Daniel, it worked okay your suggestion, thanks for your attention!

2 answers

1

Replaces Alert by field value assignment:

<input ID="txCNPJ_cad_emp" name="cnpj" class="form-control" placeholder="Digite o CNPJ" onkeyup="FormataCnpj(this,event)" onblur="if(!validarCNPJ(this.value)){this.value = 'CNPJ inválido'; this.value='';}" required autofocus>

Note that in condition true is setting empty value this.value='';. That’s the way you want it?

0


I suggest removing the direct declared event return test in the element to make it better for you to view:

<input ID="txCNPJ_cad_emp" id="cnpj" name="cnpj" class="form-control" placeholder="Digite o CNPJ" onkeyup="FormataCnpj(this,event)" onblur="verificarValidacaoCNPJ()" required autofocus></>

I also changed the HTML a little to add an id, since both elements (inpt of cnpj and msg validation) have the same name.

Treatment in function called on onblur:

function verificarValidacaoCNPJ(){
    var valCNPJ = !document.getElementById("cnpj")? "" : document.getElementById("cnpj").value;
    if(!validarCNPJ(valCNPJ))
        document.getElementById("txCNPJ_cad_emp").value = "CNPJ inválido";
    else
        document.getElementById("txCNPJ_cad_emp").value = "CNPJ válido";
}
  • I changed how you indicated, but it didn’t work and debugging it gives the following error: Uncaught TypeError: Cannot read property 'value' of null&#xA; at verificarValidacaoCNPJ (cnpj.html:84)&#xA; at HTMLInputElement.onblur (cnpj.html:53)&#xA;verificarValidacaoCNPJ @ cnpj.html:84&#xA;onblur @ cnpj.html:53

  • I changed the function a little. When you lose focus cnpj field has values there? Can you debug js?

  • it worked @Aline, it is because it has a mask for that field then was causing the error. Thank you

Browser other questions tagged

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