How to specify in javascript the set of inputs that have been cloned

Asked

Viewed 97 times

0

I am set up a request system that takes information from the database and fills the fields with it.

Follow the request code that fills the fields with the information:

$(document).ready(function(){
    $(".nome_prod").on("focusout", function(){
        var $cod_prod = $(".cod_prod");
        var $quantidade = $(".quantidade");
        var $valor_uni = $(".valor_uni");
        $.getJSON('function2.php',{ 
            nome_prod: $( this ).val() 
        },function( json ){
            $cod_prod.val( json.cod_prod );
            $quantidade.val( json.quantidade );
            $valor_uni.val( json.valor_uni );
        });
    });
});

The code that clones the fields:

function duplicarCampos(){
    var clone = document.getElementById('origem').cloneNode(true);
    var destino = document.getElementById('destino');
    destino.appendChild (clone);

    var camposClonados = clone.getElementsByTagName('input');

    for(i=0; i<camposClonados.length;i++){
        camposClonados[i].value = '';
    }
}

function removerCampos(id){
    var node1 = document.getElementById('destino');
    node1.removeChild(node1.childNodes[0]);
}

and the function2.php

include_once("connections/conn2.php");

function retorna($nome_prod, $conn1){
    $result_prod = "SELECT * FROM cad_produtos WHERE nome_prod = '$nome_prod' LIMIT 1";
    $resultado_prod = mysqli_query($conn1, $result_prod);

    if($resultado_prod->num_rows){
        $row_prod = mysqli_fetch_assoc($resultado_prod);
        $valores['nome_prod'] = $row_prod['nome_prod'];
        $valores['quantidade'] = $row_prod['uni_med'];
        $valores['valor_uni'] = $row_prod['valor_uni'];
        $valores['cod_prod'] = $row_prod['codigo_prod'];
    }
    else{
    }

    return json_encode($valores);
}

if(isset($_GET['nome_prod'])){
    echo retorna($_GET['nome_prod'], $conn1);
}

When I duplicate the field it does not work, but when I click on the first field it fills all others with the same information contained in the first field.

The fields that are cloned are in the original div and are cloned to target div but they only copy the information from the first field

<div id="origem">
    <div class="row">
        <div class="col-md-2 col-xs-2">
            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <div class="input-group-text">
                            <i class="fa fa-barcode"></i>
                        </div>
                    </div>
                    <input id="cod_prod" name="cod_prod[]" placeholder="Codigo do produto" type="text" class="form-control cod_prod">
                </div>
            </div>
        </div>
        <div class="col-md-4 col-xs-4">
            <div class="form-group ">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <div class="input-group-text">
                            <i class="fa fa-align-justify"></i>
                        </div>
                    </div>
                    <input id="descricao" name="nome_prod[]" placeholder="Descrição" type="text" class="form-control nome_prod">
                </div>
            </div>
        </div>
        <div class="col-md-2 col-xs-2">
            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <div class="input-group-text">
                            <i class="fa fa-money"></i>
                        </div>
                    </div>
                    <input id="valor" name="valor_uni[]" placeholder="Valor" type="text" class="form-control valor_uni">
                </div>
            </div>
        </div>
        <div class="col-md-2 col-xs-2">
            <div class="form-group">
                <div class="input-group">
                    <div class="input-group-prepend">
                        <div class="input-group-text">
                            <i class="fa fa-money"></i>
                        </div>
                    </div>
                    <input id="valor" name="quantidade[]" placeholder="Quantidade" type="text" class="form-control quantidade">
                </div>
            </div>
        </div>
    </div>
</div>
<div id="destino">
</div>

imagem com os campo clonados

  • @Leonardobuta this question I mentioned to you

  • I can’t analyze it now to give an answer. But before anyone can do it, improve the question, it is confused, it is difficult to understand both the goal and the error.

  • Let me get this straight. You have a page that returns data from your database in a form. Now you want to create a way to duplicate that data to create a new entry in the database, that’s it?

  • I updated the question of a look there please

  • i have a code that completes the fields with information coming from the bank, I just type the name and the information completes the other input fields but it is not completing there when I click on the first field it completes but copying the other information

  • You’ve made it easy enough to understand.

  • Not related to the question, but already a framework to make your work easier? Something like Laravel or Cakephp, for example?

  • so I’ve never used any framework, I know it makes it easier but as a beginner I have a lot to learn yet

  • 1

    I already see something wrong: when you clone the div #origem, you’re duplicating both the id #origem as the id’s of the elements within that div. If you’re still learning HTML, know that an id should be unique on the page, meaning there can’t be two elements with the same id #origem (or other id’s). Use class instead.

  • I know it was just inattention

  • the problem is that this not giving id conflict as usual

Show 6 more comments

1 answer

2


I confess it was quite difficult to understand what you intend to do. From the description in the question it seems much more complicated than actually (I believe) it is the goal. The question is also not well written, with many Portuguese errors and poorly formatted code. This complicates the understanding of the question, removing the possibility of receiving answers.

There are also numerous problems in the presented code, such as repetition of the ID in the inputs <input id="valor" name="valor_uni[]" and <input id="valor" name="quantidade[]" and the attempt to take values by class, when there is more than one element with the same class (ex: var $cod_prod = $(".cod_prod");).

There also seem to be problems in UX, such as having a group of inputs in "origin" and several in destination, when it seemed necessary to have only one "group" for all "lines" of inputs. If this is not the goal, ideally "origin" and "destiny" should be visually distinct. On the other hand, if all the lines were removed, it would not be possible to create a new one either. To solve this, it would be necessary to copy the inputs from a "template" and not from an existing div.

The removal part is also strange, because it always removes the "first" line of "destination", and it is not possible to remove a specific.

I will present a solution disregarding the above problems and believing that you have 2 objectives:

  • "Clone" a set of inputs;
  • Fill in a set of inputs with values from your backend.

function duplicarCampos() {
  var destino = $('#destino');
  var clone = $('#origem').children().clone(true, true);

  // limpa valores
  clone.find('input:text').val('');

  destino.append(clone);
}

function removerCampos() {
  $('#destino').find('div:first').remove();
}

$(document).ready(function() {
  $("#duplicarCampos").click(duplicarCampos);
  $("#removerCampos").click(removerCampos);

  $(".nome_prod").on("focusout", function() {
    var parent = $(this).closest('div.row');
    var cod_prod = parent.find(".cod_prod");
    var quantidade = parent.find(".quantidade");
    var valor_uni = parent.find(".valor_uni");

    cod_prod.val("json.cod_prod");
    quantidade.val("json.quantidade");
    valor_uni.val("json.valor_uni");

    //$.getJSON('function2.php', {
    //  nome_prod: $(this).val()
    //}, function(json) {
    //  cod_prod.val(json.cod_prod);
    //  quantidade.val(json.quantidade);
    //  valor_uni.val(json.valor_uni);
    //});
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button id="duplicarCampos">Duplicar</button>
<button id="removerCampos">Remover</button>

<div id="origem">
  <div class="row">
    <div class="col-md-2 col-xs-2">
      <div class="form-group">
        <div class="input-group">
          <div class="input-group-prepend">
            <div class="input-group-text">
              <i class="fa fa-barcode"></i>
            </div>
          </div>
          <input name="cod_prod[]" placeholder="Codigo do produto" type="text" class="form-control cod_prod">
        </div>
      </div>
    </div>
    <div class="col-md-4 col-xs-4">
      <div class="form-group ">
        <div class="input-group">
          <div class="input-group-prepend">
            <div class="input-group-text">
              <i class="fa fa-align-justify"></i>
            </div>
          </div>
          <input name="nome_prod[]" placeholder="Descrição" type="text" class="form-control nome_prod">
        </div>
      </div>
    </div>
    <div class="col-md-2 col-xs-2">
      <div class="form-group">
        <div class="input-group">
          <div class="input-group-prepend">
            <div class="input-group-text">
              <i class="fa fa-money"></i>
            </div>
          </div>
          <input name="valor_uni[]" placeholder="Valor" type="text" class="form-control valor_uni">
        </div>
      </div>
    </div>
    <div class="col-md-2 col-xs-2">
      <div class="form-group">
        <div class="input-group">
          <div class="input-group-prepend">
            <div class="input-group-text">
              <i class="fa fa-money"></i>
            </div>
          </div>
          <input name="quantidade[]" placeholder="Quantidade" type="text" class="form-control quantidade">
        </div>
      </div>
    </div>
  </div>
</div>

<div id="destino"></div>

  • Really @tvdias had these problems even, I was already desperate, this is not my source code but as I had already tested several solutions it turned out that the code got several errors that I was slowly noticing, but thanks for helping me

  • @Danielricardo, if you can help in any way, says

  • mano vlw even worked perfectly now with this solved I will solve the rest of the problems haha

  • hello all right, could you help me, I’m having a problem but it wouldn’t be possible to create a question, why it’s complicated to explain, is there any way I can get in touch with you?

Browser other questions tagged

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