Javascript function not active in input

Asked

Viewed 76 times

0

inserir a descrição da imagem aqui

Good night. Notice the image above, I have a form and in it I use Abels that fix themselves at the top (example of CEP input there) when I type something into them (JS input event). So far so good, the problem is that I have a JS that automatically looks for the address when I type the zip code and fills in for me the inputs, and with that, the Abels do not fix at the top (because I did not type anything to activate the input event).

I wanted to know if there is a way (of course there is) to fix these Abels as soon as I gave an onblur in the CEP field, and return them to the place of origin when the inputs were empty.

Follow the codes (I couldn’t get Jquery to work here, but the code is right):

// fixar descrição do campo
function fixarDescricao() {
    var campo = $('.campo-formulario');
    var descricao = $('.descricao-campo');
    campo.on('input',function(){
        var descricaoAtual = $(this).parent().find('.descricao-campo');
       if($(this).val().length > 0){
           descricaoAtual.addClass('descricao-fixa');
       } else{
           descricaoAtual.removeClass('descricao-fixa');
       }
    });  
}

//busca o cep
function limpa_formulário_cep() {
                //Limpa valores do formulário de cep.
                document.getElementById('logradouro').value=("");
                document.getElementById('estado').value=("");
                document.getElementById('cidade').value=("");
                document.getElementById('bairro').value=("");
        }

        function meu_callback(conteudo) {
            if (!("erro" in conteudo)) {
                //Atualiza os campos com os valores.
                document.getElementById('logradouro').value=(conteudo.logradouro);
                document.getElementById('estado').value=(conteudo.uf);
                document.getElementById('cidade').value=(conteudo.localidade);
                document.getElementById('bairro').value=(conteudo.bairro);
            } //end if.
            else {
                //CEP não Encontrado.
                limpa_formulário_cep();
                alert("CEP não encontrado.");
            }
        }

        function pesquisacep(valor) {

            //Nova variável "cep" somente com dígitos.
            var cep = valor.replace(/\D/g, '');

            //Verifica se campo cep possui valor informado.
            if (cep != "") {

                //Expressão regular para validar o CEP.
                var validacep = /^[0-9]{8}$/;

                //Valida o formato do CEP.
                if(validacep.test(cep)) {

                    //Preenche os campos com "..." enquanto consulta webservice.
                    document.getElementById('logradouro').value="...";
                    document.getElementById('estado').value="...";
                    document.getElementById('cidade').value="...";
                    document.getElementById('bairro').value="...";

                    //Cria um elemento javascript.
                    var script = document.createElement('script');

                    //Sincroniza com o callback.
                    script.src = 'https://viacep.com.br/ws/'+ cep + '/json/?callback=meu_callback';

                    //Insere script no documento e carrega o conteúdo.
                    document.body.appendChild(script);

                } //end if.
                else {
                    //cep é inválido.
                    limpa_formulário_cep();
                    alert("Formato de CEP inválido.");
                }
            } //end if.
            else {
                //cep sem valor, limpa formulário.
                limpa_formulário_cep();
            }
        };
input, select {
    outline: none;
    width: 100%;
    border: 1px solid #999;
    height: 45px;
    padding: 0 15px;
    font-family: 'Texto';
    color: #222;
    font-size: 105%;
    background: none;
    z-index: 3;
    margin-bottom: 20px;
    border-radius: 6px;
}

.container-campo {
    width: 100%;
    position: relative;
}

.descricao-campo {
    position: absolute;
    left: 15px;
    top: 10px;
    transition: all .2s;
    cursor: text;
    z-index: 1;
    -webkit-user-select: none;
       -moz-user-select: -moz-none;
        -ms-user-select: none;
            user-select: none;
}

.descricao-fixa {
    top: -10px;
    left: 8px;
    transition: all .2s;
    z-index: 3;
    background: #fff;
    padding: 0 5px;
    font-size: 80%;
    font-weight: bold;
}

input:focus ~ .descricao-campo , select:focus ~ .descricao-campo {
    top: -10px;
    left: 8px;
    transition: all .2s;
    z-index: 3;
    background: #fff;
    padding: 0 5px;
    font-size: 80%;
    color: dodgerblue;
    font-weight: bold;
}

input:focus , select:focus {
    border: 2px solid dodgerblue; 
}

.campos-dados-funcionario, .campos-dados-endereco, .campos-dados-venda {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-top: 30px;
}

.dados-funcionario, .dados-endereco, .dados-venda {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    animation: slideUp 1.3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section class="dados-endereco">
                                <p class="titulo-secao">endereço e contato</p>
                                <div class="campos-dados-endereco">
                                    <div class="container-campo">
                                        <input type="text" name="cep" class="campo-formulario" id="cep" onblur="pesquisacep(this.value);" required>
                                        <label class="descricao-campo" for="cep">CEP<span class="campo-obrigatorio">*</span></label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="logradouro" class="campo-formulario" id="logradouro" required>
                                        <label class="descricao-campo" for="logradouro">Logradouro<span class="campo-obrigatorio">*</span></label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="number" name="numero_casa" class="campo-formulario" id="numero_casa" required>
                                        <label class="descricao-campo" for="numero_casa">Número<span class="campo-obrigatorio">*</span></label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="complemento" class="campo-formulario" id="complemento">
                                        <label class="descricao-campo" for="complemento">Complemento</label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="estado" class="campo-formulario" id="estado" required>
                                        <label class="descricao-campo" for="estado">Estado<span class="campo-obrigatorio">*</span></label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="cidade" class="campo-formulario" id="cidade" required>
                                        <label class="descricao-campo" for="cidade">Cidade<span class="campo-obrigatorio">*</span></label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="bairro" class="campo-formulario" id="bairro" required>
                                        <label class="descricao-campo" for="bairro">Bairro<span class="campo-obrigatorio">*</span></label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="email" class="campo-formulario" id="email">
                                        <label class="descricao-campo" for="email">E-mail</label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="telefone" class="campo-formulario" id="telefone">
                                        <label class="descricao-campo" for="telefone">Telefone</label>
                                    </div>
                                    <div class="container-campo">
                                        <input type="text" name="celular" class="campo-formulario" id="celular">
                                        <label class="descricao-campo" for="celular">Celular</label>
                                    </div>
                                </div>
                            </section>

  • After the "query" function is executed, try calling the event "keydown" for each input that has been changed.

  • Dude I’m pretty bad with JS, would you give me an example of how I could do that?

1 answer

1


$(document).ready(function() {
  $(".campo-formulario").on("keydown change", function() {
    var elem = $(this);
    var siblings = elem.siblings();
    if (elem.val().length > 0) {
      siblings.addClass('focused');
    } else {
      siblings.removeClass('focused');
    }
  });
});

altered:

document.getElementById('logradouro').value = (conteudo.logradouro);

for:

 $("#logradouro").val(conteudo.logradouro).keydown();

I put it in the plunker, forehead here

  • this almost worked, but I needed the "focused" class to be added without I need to give a Focus in the field, I would have to activate when I left the zip code field

  • altered, forehead again.

  • now yes!! thank you very much bro.

  • s2 mass, if successful, accepted as answer.

Browser other questions tagged

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