Limit the amount of fields with Jquery

Asked

Viewed 93 times

1

I am doing the size registration on a system as follows:

inserir a descrição da imagem aqui

It is working perfectly, but now I need to limit the inclusion of up to 03 Sizes, but I am not able to do. Follows below the code:

<table border="0">
    <tr class='linhas'>
        <td  style="padding: 5px"><input type="text" name="Cores[]" class="form-control" placeholder="Cor do Produto" value=""></td>
        <td  style="padding: 5px"><input type="text" name="Tamanho[]" class="form-control" placeholder="Tamanho" value=""></td>
        <td  style="padding: 5px"><input type="number" name="EstoqueProd[]" class="form-control pull-left" placeholder="Estoque" min="1" value=""></td>
        <td  style="padding: 5px"><button type="button" class="removerCampo btn btn-danger" title="Remover linha"><i class="fa fa-minus-square" aria-hidden="true"></i> Remover</button></td>
    </tr>
    <tr>
        <td colspan="3"><button type="button" class="adicionarCampo btn btn-primary" title="Adicionar item"><i class="fa fa-plus-square" aria-hidden="true"></i> Adicionar mais tamanhos</button></td>
    </tr>
</table> 

<script type="text/javascript">
     $(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[type="text"]').val("");
             novoCampo.find('select').val("");
             novoCampo.insertAfter("tr.linhas:last");
             removeCampo();
       });
     });
 </script>

1 answer

3


In the event of the button adicionarCampo count the amount of fields you already have in the DOM:

$(".adicionarCampo").click(function () {
    if ($('.linhas').length < 3) {
        novoCampo = $("tr.linhas:first").clone();
        novoCampo.find('input[type="text"]').val("");
        novoCampo.find('select').val("");
        novoCampo.insertAfter("tr.linhas:last");
        removeCampo();
    }
});
  • Thank you very much arllondias. It worked!

  • 1

    You’re welcome! @Fox.11

Browser other questions tagged

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