Jquery does not exclude rows from the table

Asked

Viewed 83 times

2

I have the form below which when I click Add more Pet, he adds one more panel normally:

inserir a descrição da imagem aqui

But when I click Remove, it removes only buttons and panels continue. See code:

<table border="0" style="width: 100%">
            <tr class='linhas'>
            <td>
                <div class="panel panel-primary">
                 <div class="panel-heading">
                   <i class="fa fa-paw fa-lg" aria-hidden="true"></i>  DADOS DO PET
                  </div>
                 <div class="panel-body">
                     <div class="table-responsive">
                         <div class="form-group">
                          <label>Espécie:</label>
                          <select name="Especie" class="form-control">
                            <option value="Canino">Canino</option>
                            <option value="Felino">Felino</option>
                          </select>
                        </div>
                        <div class="form-group">
                         <label>Nome do Pet:</label>
                         <input type="text" name="NomePet" class="form-control" required="required">
                        </div>
                        <div class="form-group">
                         <label>Aniversário do Pet:</label>
                         <input type="date" name="AniversarioPet" class="form-control" data-inputmask="'alias': '99/99/9999'" required="required">
                       </div>
                       <div class="form-group">
                        <label>Gênero:</label>
                         <div class="checkbox">
                           <label><input type="radio" name="SexoPet" value="Macho" checked> Macho</label>
                           <label><input type="radio" name="SexoPet" value="Fêmea"> Fêmea</label>
                         </div>
                      </div>
                      <div class="form-group">
                       <label>Idade:</label>
                       <select name="IdadePet" class="form-control">
                         <option value="Antes dos 11 meses">Antes dos 11 meses</option>
                         <option value="Entre 1 e 8 anos">Entre 1 e 8 anos</option>
                       </select>
                     </div>
                    </div>
                 </div>
             </div>
       </td>
     </tr>
    <tr>
      <td>
        <button type="button" class="adicionarCampo btn btn-primary" title="Adicionar item"><i class="fa fa-plus-square" aria-hidden="true"></i> Adicionar mais Pet</button>
        <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>
</table>

JQUERY

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

What I find strange is when I put the line down inside a TD as another column where the panel is, works:

<button type="button" class="removerCampo btn btn-danger" title="Remover linha"><i class="fa fa-minus-square" aria-hidden="true"></i> Remover</button>

How can I fix this?

  • 1

    Fox puts the CSS? also for me to assemble the fiddle? much better bro. Thanks

  • Hello Leonardo. I’m actually using Bootstrap. I don’t have a specific CSS for it. It’s just these codes that make up the question even.

  • 1

    All right, it was more my habit of leaving the cute fiddle kkk, I solved the problem I’m just explaining why you were behaving like that 1min.

2 answers

2


You were using $(this).parent().parent().remove(); that is, from the bottom up the elements were: button > td > tr you were removing the tr that composes the two buttons and not the tr that composes the form fields.

The solution was: $("tr.linhas:last").remove(); the same way you used novoCampo.insertAfter("tr.linhas:last"); I used to remove the last element added.

OBS: I believe that what you are doing in the logic of removing PET hurts the concepts of UX, because let’s say that you have put 300 PETS, and decide to remove the second from that list, you will have to remove 298 to get to the second. Tries to add independent buttons. ;)

$("#remove").click(function() {
  if ($("tr.linhas").length > 1) {
    $("tr.linhas:last").remove();
  };
});


$(".adicionarCampo").click(function() {
  novoCampo = $("tr.linhas:first").clone();
  novoCampo.find('input[type="text"]').val("");
  novoCampo.find('select').val("");
  novoCampo.insertAfter("tr.linhas:last");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="0" style="width: 100%">
  <tr class='linhas'>
    <td>
      <div class="panel panel-primary">
        <div class="panel-heading">
          <i class="fa fa-paw fa-lg" aria-hidden="true"></i> DADOS DO PET
        </div>
        <div class="panel-body">
          <div class="table-responsive">
            <div class="form-group">
              <label>Espécie:</label>
              <select name="Especie" class="form-control">
                            <option value="Canino">Canino</option>
                            <option value="Felino">Felino</option>
                          </select>
            </div>
            <div class="form-group">
              <label>Nome do Pet:</label>
              <input type="text" name="NomePet" class="form-control" required="required">
            </div>
            <div class="form-group">
              <label>Aniversário do Pet:</label>
              <input type="date" name="AniversarioPet" class="form-control" data-inputmask="'alias': '99/99/9999'" required="required">
            </div>
            <div class="form-group">
              <label>Gênero:</label>
              <div class="checkbox">
                <label><input type="radio" name="SexoPet" value="Macho" checked> Macho</label>
                <label><input type="radio" name="SexoPet" value="Fêmea"> Fêmea</label>
              </div>
            </div>
            <div class="form-group">
              <label>Idade:</label>
              <select name="IdadePet" class="form-control">
                         <option value="Antes dos 11 meses">Antes dos 11 meses</option>
                         <option value="Entre 1 e 8 anos">Entre 1 e 8 anos</option>
                       </select>
            </div>
          </div>
        </div>
      </div>
    </td>
  </tr>
  <tr>
    <td>
      <button type="button" class="adicionarCampo btn btn-primary" title="Adicionar item"><i class="fa fa-plus-square" aria-hidden="true"></i> Adicionar mais Pet</button>
      <button type="button" id="remove" class="removerCampo btn btn-danger" title="Remover linha"><i class="fa fa-minus-square" aria-hidden="true"></i> Remover</button>
    </td>
  </tr>
</table>

  • Perfect Leonardo. It worked! Actually I will limit only 10 Pets. Thank you so much for your help.

  • 1

    You’re Welcome !

0

Formatting logic is not cool, use <table> for tabular data only, but if you still want to use <table>, let the add and remove buttons off the table.

Simple example using jQuery:

$(function(){ 
  var pets = $('.pets');
  var maximo_de_pets = 10;
  $('.add').click(function(){
    if (pets.find('tr').length < maximo_de_pets){
      var novo_pet = pets.find('tr').first().clone();
      novo_pet.find('input[type="text"]').val("");
      novo_pet.find('select').val("");
      pets.append(novo_pet);
    }
    else{
    	alert('maximo ' + maximo_de_pets + ' pets')
    }
  });
  $('.conteudo').on('click', '.remover', function(){
    if(pets.find('tr').length > 1){
      if ($(this).hasClass('ultimo')){
        pets.find('tr').last().remove();
      }
      else{
        $(this).closest('tr').remove();
      }
    }
    else{
      alert('minimo 1 pet');
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='conteudo'>
<table class="pets">
<tr><td>blabla <button class='remover'>remover</button></td></tr>
</table>
<div class="botoes">
  <button class="add">Adicionar</button>
  <button class="remover ultimo">Remover ultimo</button>
</div>
</div>

Browser other questions tagged

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