ajax post with dynamic input

1

I have a form with a input that is created dynamically, as follows:

<tr class="linhas">
                    <td align="right">Inicio:</td>
                    <td align="left"><input name="inicio[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /></td>
                    <td align="right">Término:</td>
                    <td align="left"><input name="termino[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /> <a href="#" class="removerCampo" title="Remover linha"><img src="imagens/exc_btn.png" border="0" /></a></td>
                </tr>


<script type="text/javascript">


    $(document).ready(function() {
        $(".data").mask("99/99/9999");
    $(function () {
      function removeCampo() {
        $(".removerCampo").unbind("click");
        $(".removerCampo").bind("click", function () {
           if($("tr.linhas").length > 1){
            $(this).parent().parent().remove();
           }
        });
      }

      $(".adicionarCampo").click(function () {
        novoCampo = $("tr.linhas:first").clone();
        novoCampo.find("input").val("");
        novoCampo.insertAfter("tr.linhas:last");
        removeCampo();
        $(".data").mask("99/99/9999");

      });

    }); 
 });    

The form itself works fine, the problem is that I can not get the dynamic values of the start and end, follow the code:

function SalvarRegistro(){
        var inicio = $("input[name='inicio[]']").val();
        var termino = $("input[name='termino[]']").val();

        $.ajax({
            type: "POST",
            dataType: "json",
            url: "acao/cadastro_averbacao1.php",
            data: {inicio: inicio, termino: termino},
            success: function(data) {
                if(data.sucesso == 0){
                    swal({ 
                title: "Sucesso",
                text: data.msg,
                type: "success" 
                },
                function(){
                parent.location.href = parent.location.href;
                });
                }else{
                swal({ 
                title: "Um erro ocorreu",
                text: data.msg,
                type: "error" 
                }); 
                }
                    },
            failure: function() {
            swal({ 
                title: "Um erro ocorreu",
                text: "Usuário não encontrado verifique o número digitado!",
                type: "error" 
                },
                function(){
                parent.location.href = parent.location.href;
                });
            }
        });

    return true;
}
    
asked by anonymous 31.08.2016 / 03:34

1 answer

2

Since there may be multiple elements with the same name, you need to check the value of each element.

And the values can be put in arrays , in case one for the beginning and another for the term.

I've done an example below with displaying the values of the dynamic fields:

  $(document).ready(function() {
    
    $('#btn').click(function(){
        SalvarRegistro();
    });
    
    
       // $(".data").mask("99/99/9999"); // comentei a máscara pois não sei qual lib você usou
    $(function () {
      function removeCampo() {
        $(".removerCampo").unbind("click");
        $(".removerCampo").bind("click", function () {
           if($("tr.linhas").length > 1){
            $(this).parent().parent().remove();
           }
        });
      }

      $(".adicionarCampo").click(function () {
        novoCampo = $("tr.linhas:first").clone();
        novoCampo.find("input").val("");
        novoCampo.insertAfter("tr.linhas:last");
        removeCampo();
        //$(".data").mask("99/99/9999"); // comentei a máscara pois não sei qual lib você usou

      });

    }); 
 });    


function SalvarRegistro(){
        var inicio = [];
        var termino = [];
        $("input[name='inicio[]']").each(function(){
             inicio.push($(this).val());
        });


        $("input[name='termino[]']").each(function(){
             termino.push($(this).val());
        });

         alert('inicio: ' + inicio);
         alert('termino: ' + termino);
  
  
        $.ajax({
            type: "POST",
            dataType: "json",
            url: "acao/cadastro_averbacao1.php",
            data: {inicio: inicio, termino: termino},
            success: function(data) {
                if(data.sucesso == 0){
                    swal({ 
                title: "Sucesso",
                text: data.msg,
                type: "success" 
                },
                function(){
                parent.location.href = parent.location.href;
                });
                }else{
                swal({ 
                title: "Um erro ocorreu",
                text: data.msg,
                type: "error" 
                }); 
                }
                    },
            failure: function() {
            swal({ 
                title: "Um erro ocorreu",
                text: "Usuário não encontrado verifique o número digitado!",
                type: "error" 
                },
                function(){
                parent.location.href = parent.location.href;
                });
            }
        });

    return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><trclass="linhas">
                    <td align="right">Inicio:</td>
                    <td align="left"><input name="inicio[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /></td>
                    <td align="right">Término:</td>
                    <td align="left"><input name="termino[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /> <a href="#" class="removerCampo" title="Remover linha"><img src="imagens/exc_btn.png" border="0" /></a></td>
                </tr>

   <tr class="linhas">
                    <td align="right">Inicio:</td>
                    <td align="left"><input name="inicio[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /></td>
                    <td align="right">Término:</td>
                    <td align="left"><input name="termino[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /> <a href="#" class="removerCampo" title="Remover linha"><img src="imagens/exc_btn.png" border="0" /></a></td>
                </tr>

   <tr class="linhas">
                    <td align="right">Inicio:</td>
                    <td align="left"><input name="inicio[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /></td>
                    <td align="right">Término:</td>
                    <td align="left"><input name="termino[]" class="data" type="text" value="" style="font-size: 12pt; font-weight: bold; width: 130px" /> <a href="#" class="removerCampo" title="Remover linha"><img src="imagens/exc_btn.png" border="0" /></a></td>
                </tr>
</table>
<input type="button" id="btn" value="Salvar"/>
    
31.08.2016 / 03:56