Using a JS Function for multiple INPUTS

Asked

Viewed 48 times

-1

Good afternoon to all,

I’m new here and I hope I can explain my problem.

I have a register of branches, of which I made a button to add new lines according to code. But I have a Function where it finds the zip code and puts the data in its proper fields. I would like this Function to work for all the new inputs I’m adding.

                            <div class="list1" id="filiais" style="display: none;">
                                <input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ">
                                <input type="text"  name="filial2[]" id="cep1" placeholder="CEP">
                                <input type="text" name="filial3[]"  id="bairro" placeholder="BAIRRO">
                                <input type="text" name="filial4[]" id="cidade1" placeholder="CIDADE/UF">
                                <input type="number" name="filial5[]" id="colab" Placeholder="Nº ¹">
                                <input type="number" name="filial6[]" id="colab" Placeholder="Nº ²">
                                <input type="button" id="add-campo" class="bt-vd" value="+" ><br/>
                            </div><br/>

And this is the code where I add the new line

        $( '#add-campo' ).click(function() {

          $( "#filiais" ).append( '<input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ"> <input type="text"  name="filial2[]" id="cep1" placeholder="CEP">\
           <input type="text" name="filial3[]"  id="bairro" placeholder="BAIRRO"> <input type="text" name="filial4[]" id="cidade1" placeholder="CIDADE/UF">\
           <input type="number" name="filial5[]" id="colab" Placeholder="Nº ¹"> <input type="number" name="filial6[]" id="colab" Placeholder="Nº ²">' );
        });

and the CEP code

$(document).ready(function(){
$(document).on('change','input#cep1', function() {

    //Nova variável "cep" somente com dígitos.

    var cep1 = $(this).val();
    var cep = cep1.replace("-" , "")


    //Verifica se campo cep possui valor informado.
    if (cep != "") {
        var validacep = /^[0-9]{8}$/;
        if(validacep.test(cep)) {
            $.getJSON("https://viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {

                if (!("erro" in dados)) {
                    //Atualiza os campos com os valores da consulta.
                    $("input#bairro1").val(dados.bairro);
                    $("input#cidade1").val(dados.localidade + "/" + dados.uf)

                } //end if.
                else {
                    limpa_formulário_cep();
                    alert("CEP não encontrado.");
                }
            });
        } //end if.
        else {
            alert("Formato de CEP inválido.");
        }
    } //end if.
    else {
    }
});
});
Obrigado.
  • There are two problems I see there. 1) You are inserting the same id every time you click the button (id should be single); 2) In the CEP function, you only add the Listener in the CEP element that already exists, you would need to add this Listener in the new line as well when creating it

1 answer

0

Hello, all good?

It’s happening the seguite, when you add the inputs by function, all inputs have the same ID, so they are various inputs with the id="bairro1". Then the second function tries to select the id="bairro1", but since it has several ids with the same name, it selects the first one and always changes the value of the first one. Different from what you expect.

To solve this you have to put the Istener onchange in the CEP input tag itself, then you will be able to pass the input attributes to the function in question and his relatives, to help in this mission I have grouped the inputs with a fieldset.

Look how it turned out:

$('#add-campo').click(function() {
  $("#filiais").append('<fieldset style="border: none"> <input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ"> <input type="text"  name="filial2[]" id="cep" placeholder="CEP" onchange="fillInfos(this)"> <input type="text" name="filial3[]"  id="bairro" placeholder="BAIRRO"> <input type="text" name="filial4[]" id="cidade" placeholder="CIDADE/UF"> <input type="number" name="filial5[]" id="colab1" Placeholder="Nº ¹"> <input type="number" name="filial6[]" id="colab2" Placeholder="Nº ²"> </fieldset>');
});

function fillInfos(input) {
  var cep = input.value.replace("-", "");
  var validacep = /^[0-9]{8}$/;
  if (validacep.test(cep)) {
    $.getJSON("https://viacep.com.br/ws/" + cep + "/json/?callback=?", function(dados) {
      if (!("erro" in dados)) {
        input.parentElement.childNodes[5].value = dados.bairro;
        input.parentElement.childNodes[7].value = dados.localidade + "/" + dados.uf;
      } else {
        limpa_formulário_cep();
        alert("CEP não encontrado.");
      }
    })
  } else {
    alert("Formato de CEP inválido.")
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list1" id="filiais" style="display: block;">
  <fieldset style="border: none">
    <input type="text" name="filial1[]" id="cnpj" placeholder="CNPJ">
    <input type="text" name="filial2[]" id="cep" placeholder="CEP" onchange="fillInfos(this)">
    <input type="text" name="filial3[]" id="bairro" placeholder="BAIRRO">
    <input type="text" name="filial4[]" id="cidade" placeholder="CIDADE/UF">
    <input type="number" name="filial5[]" id="colab1" Placeholder="Nº ¹">
    <input type="number" name="filial6[]" id="colab2" Placeholder="Nº ²">
    <input type="button" id="add-campo" class="bt-vd" value="+">
  </fieldset>
</div><br/>

  • 1

    Oops, thank you very much, I really hadn’t thought of that. Value

Browser other questions tagged

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