Save values from fields created With Append(dynamically created field ) in the database

Asked

Viewed 48 times

0

I have the following code in JS, it creates new fields when clicking the button "+": inserir a descrição da imagem aqui

What I would need is rescue the values that are created with the append and insert them into the Database using php. Example:

 var i = 1;
    $(document).ready(function() {
    
        
    $('#add_div').click (function(e) {
    
    if (i < 100) {
        var a = window.document.getElementById('area')
    
        $('#idDiv').append('<div class="form-row">\
            <div class="form-group col-md-2"><input type="text" class="form-control campoDefault" placeholder="Material" onchange='+buscar_dados_sap+' name="material'+[i]+'" id="material'+[i]+'" /></div>\
            <div class="form-group col-md-2"><input type="text" class="form-control campoDefault" placeholder="Descrição" name="descricao'+[i]+'" id="descricao'+[i]+'"  /></div>\
            <div class="form-group col-md-1"> <input type="text" class="form-control campoDefault" placeholder="Depósito" name="deposito'+[i]+'" id="deposito'+[i]+'" /></div>\
            <div class="form-group col-md-1"><input type="text" class="form-control campoDefault" placeholder="UM" name="um'+[i]+'" id="um'+[i]+'"  required /></div>\
            <div class="form-group col-md-1"> <input type="text" class="form-control campoDefault" placeholder="QTD" name="qtd'+[i]+'" id="qtd'+[i]+'" onchange='+buscar_dados_sap+' novocampo"/></div>\
            <div class="form-group col-md-2"> <input type="text" class="form-control campoDefault" placeholder="Unitátio" name="valor'+[i]+'" id="valor'+[i]+'" required /></div>\
            <div class="form-group col-md-2"> <input type="text" class="form-control campoDefault" placeholder="Total" name="val_total'+[i]+'" id="val_total'+[i]+'"  required /></div>\
            <a href="#" class="remove"><font size="4">✘</font></a><br><br><br>\
            </div>'
            ); 
      
            i++;
            } });
    
    // *Remove o div anterior* //
    $('#idDiv').on("click",".remove",function(e) {
        e.preventDefault();
    $(this).parent('div').remove();
        i--;
    });
    
    });

2 answers

0

**Inserting materials into the bank with the code below: Following the "material[]" pattern that inserts each dynamically created material into an array to rescue with the following code **

     if (isset($_POST['enviar'])) { 

            include 'banco.php';

            $material = $_POST['material'];
            $descricao = $_POST['descricao'];

       
              $result = count($material);

              for ($i = 0; $i < ($result) ; $i++) {
               echo "Código Material: " . $material[$i]; 
               echo " Descrições: " . $descricao[$i] . "<br>";
               
               $materiais = $material[$i]; /*Coloca todos os materiais dentro da varialvel que será jogada no banco de dados*/
               $descricoes = $descricao[$i];
                                
              $sql2 = "insert into log_solicitacao (material, descricao)
              values ('$material[$i]', '$descricao[$i]')";
                  

0


So what you need to do is basically feed the empty array fields, no keys descricao[]:

HTML:

<div class="content">
    <div>
      <button onclick="actions.removeField()">
       -
      </button> 
      <button onclick="actions.addField()">
      +
      </button> <div data-total></div>
    </div>
    <div data-form>

    </div>

</div>

Javascript:

var actions = {
    html_inputs:'<div class="form-group col-md-2"><input type="text" class="form-control campoDefault" placeholder="Material" onchange="actions.onChange()" name="material[]" id="material{item}" /></div>\
            <div class="form-group col-md-2"><input type="text" class="form-control campoDefault" placeholder="Descrição" name="descricao[]" id="descricao{item}"  /></div>\
            <div class="form-group col-md-1"> <input type="text" class="form-control campoDefault" placeholder="Depósito" name="deposito[]" id="deposito{item}" /></div>\
            <div class="form-group col-md-1"><input type="text" class="form-control campoDefault" placeholder="UM" name="um[]" id="um{item}"  required /></div>\
            <div class="form-group col-md-1"> <input type="text" class="form-control campoDefault" placeholder="QTD" name="qtd[]" id="qtd{item}" onchange="actions.onChange()" novocampo"/></div>\
            <div class="form-group col-md-2"> <input type="text" class="form-control campoDefault" placeholder="Unitátio" name="valor[]" id="valor{item}" required /></div>\
            <div class="form-group col-md-2"> <input type="text" class="form-control campoDefault" placeholder="Total" name="val_total[]" id="val_total{item}"  required /></div>',
    element:document.querySelector('[data-form]'),
    item:document.querySelector('[data-form]').childElementCount,
    addField:function(){
        if (actions.item < 100) {
        var el = actions.element;         
        var div = document.createElement('div');
            div.setAttribute('data-item', actions.item);
                 var total_display = document.querySelector('[data-total]');
                
                 div.innerHTML = actions.html_inputs.replace(/\{item\}/gi, actions.item);
                 el.appendChild(div);
                 actions.item = el.childElementCount;
                  total_display.textContent = actions.item;
                 } else {
                    alert('Máximo permitido é 100.')
                 }
           },
      removeField:function() {
       var el = actions.element;         
           if(el.childElementCount > 1) {
            var total_display = document.querySelector('[data-total]');
            
            el.removeChild(el.lastChild);
            actions.item = el.childElementCount;
            total_display.textContent =  actions.item;
           }
         
      },
      onChange:function() {
        alert('seu script onchange...');
      }
}
actions.addField();

FIDDLE example

And in PHP, you should capture as an array your collection:

 $array_material = $_POST['material'];
 $array_descricao = $_POST['descricao']; 
 $queries_insert = [];

 if (count($array_material)) {
    foreach($array_material as $k => $material) {
       $queries_insert[] = "insert into log_solicitacao (material, descricao)
                            values ('$material', '$array_descricao[$k]')";
              
    }
 }

 $queries = implode(';', $queries_insert);
 
 $mysqli = new mysqli("localhost","user","password","banco"); 
 $mysqli->multi_query($queries);

Browser other questions tagged

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