ajax post with dynamic input

Asked

Viewed 492 times

1

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

<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 well, the problem is that I can’t get the dynamic values of the beginning and ending, 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;
}

1 answer

2


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

And the values can be placed on arrays, in the case one for the beginning and one for the end.

I made an example below with the display of dynamic field values:

  $(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>
<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>

   <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"/>

  • 1

    thank you friend had managed to serialize: var inicio = $.serialize("input[name='inicio[]']); var termino = $.serialize("input[name='termino[]']"); but this solution of yours has served me more

  • If you need to ask... if you can help... I’ll help.

Browser other questions tagged

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