Add and remove rows in a table

Asked

Viewed 57 times

0

I created my table this way with button to add and delete lines:

function addAgregado(){ 
    $("#riscos").append("<div>"+$("#riscoform").html()+"</div>"); 
} 
    
$("#tbUser").on('click', '.remover_campo', function() {
  $(this).parents('tr').remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="hs_firstname field hs-form-field">
        
          <label for="educacao">Composição do Agregado Familiar (Parentesco, Nome e Idade) <span style="color: red;">*</span></label>

          <button type="button" class="hs-button primary large" onclick="addAgregado()" >Adicionar Familiar</button>
          
        </div>
         <div class="hs_firstname field hs-form-field" id="riscos">
     
     </div>
     
     <div id="riscoform" > 
            <table class="campo" cellspacing="10" id="tbUser"> 
            <tr class="elimininput">
            <td style="display: none;">
                <div class="hs_firstname field hs-form-field">

                    <label for="IdAgreg">Id </label>
                    
                    <input name="IdAgreg[]" type="text" >

                </div>

            </td> 
            <td>
                <div class="hs_firstname field hs-form-field">

                    <label for="Parent">Parentesco </label>

                    <input name="Parent[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório" >
                    <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                    </span>
                </div>

            </td> 
            <td> 
                <div class="hs_firstname field hs-form-field">

                    <label for="ParentNome">Nome </label>

                    <input name="ParentNome[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório" >
                    <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                    </span>
                </div> 
            </td> 
            <td>
                <div class="hs_firstname field hs-form-field">

                    <label for="ParentIdade">Idade </label>

                    <input name="ParentIdade[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório" >
                    <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                    </span>
                </div> 
            </td>
            <td><button class="remover_campo"><i class="fa fa-trash"></i></button></td> 
            </tr> 
                
            </table> 

            </div>

If only adding lines works correctly, the problem is when eliminating lines. After deleting a line I can’t add or delete any more lines.

  • 1

    Bruno, you are making clone of a div that has elements with ID, and the ID should be unique, this is wrong. In addition, if you created a new event, you need to assign the click event, events are not copied when you do the append

2 answers

2

By making that line: $("#riscos").append("<div>"+$("#riscoform").html()+"</div>"); is cloning whatever is in the div "riscoform". Note that right at the beginning has a table with ID, and there could be more than one element with the same ID in the DOM, this is not good.

The idea would be to change that, and soon you’ll have to change that selector: $("#tbUser").

You can then remove the ID and use the class in the selector but, as you are cloning from an existing line, the methods remove() a moment will remove all lines, which will make it impossible to clone, so you should add a protection, for example counting the remaining elements and not remove being is less than or equal to 1, for example elements with class "remover_field".

I adapted the code with these changes:

function addAgregado() {
    $("#riscos").append("<div>" + $("#riscoform").html() + "</div>");

    // no lugar o id, usei elemento+class e associa o evento
    $("table.campo").on('click', '.remover_campo', function() {
        // se for o único elemento restante, não remove
        if ($('.remover_campo').length > 1) {
            $(this).parents('tr').remove();
        }
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="hs_firstname field hs-form-field">

    <label for="educacao">Composição do Agregado Familiar (Parentesco, Nome e Idade) <span style="color: red;">*</span></label>

    <button type="button" class="hs-button primary large" onclick="addAgregado()">Adicionar Familiar</button>

</div>
<div class="hs_firstname field hs-form-field" id="riscos">

</div>

<div id="riscoform">
    <table class="campo" cellspacing="10">
        <tr class="elimininput">
            <td style="display: none;">
                <div class="hs_firstname field hs-form-field">

                    <label for="IdAgreg">Id </label>

                    <input name="IdAgreg[]" type="text">

                </div>

            </td>
            <td>
                <div class="hs_firstname field hs-form-field">

                    <label for="Parent">Parentesco </label>

                    <input name="Parent[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório">
                    <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                    </span>
                </div>

            </td>
            <td>
                <div class="hs_firstname field hs-form-field">

                    <label for="ParentNome">Nome </label>

                    <input name="ParentNome[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório">
                    <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                    </span>
                </div>
            </td>
            <td>
                <div class="hs_firstname field hs-form-field">

                    <label for="ParentIdade">Idade </label>

                    <input name="ParentIdade[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório">
                    <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                    </span>
                </div>
            </td>
            <td><button class="remover_campo"><i class="fa fa-trash"></i></button></td>
        </tr>

    </table>

</div>

  • 1

    "After deleting a line I can’t add or delete any more lines..." still has this problem in its code. But about the question code, it is too complex for something so simple, do not think?

  • I’ll give the +1 because it works if you remove the first, but if that’s the intention, it’s very strange.

1


Initially it has to be noted that the code presented in the question has a serious problem with the id attributes. Follows excerpt from the documentation:

The global id attribute defines a unique identifier (ID) that must be unique throughout the document. Its purpose is to identify the element when browsing by anchors (using a fragment identifier), when using scripts or styling (with CSS).

So far browsers impose no restrictions on violating this unique ids rule allowing websites to continue operating outside the standard HTML5.1, but as has happened in the past, and is common, as browser manufacturers direct their infrastructure to W3C standards many sites fail to function without any warning, leaving that feeling that yesterday everything worked well but waking up was all going wrong.
To resolve this issue I removed all ids and repositioning the elements regarding <label>s, because as it comes to clones of elements and shared functions I believe it is better not to depend on these.

Second point to be observed is this function:

$("#tbUser").on('click', '.remover_campo', function() {
  $(this).parents('tr').remove();
});

It instructs the browser to add the click event an element whose class is remover_campo and is the child of an element whose id is tbUser.
It turns out that this instruction performance in the form that was done occurs only once during the file loading and is only applied to the elements that are present in the Object model of the document at the time code is executed.
There is also another problem, the function of the shape that is written removes only the elements visible in the browser but the containers of those controls remained in the page structure.
Again as it comes to clones of elements and shared functions, I removed the function and passed its functionality to addAgregado() which now in addition to adding another set of elements to the page, also inserts the removal event of containers whose control is inserted.

I made a modification semantics in the document, instead of keeping the <div id="riscoform"> within the body of the document(element ) transferred to the page header(element ) within a , follows the documentation:

The HTML element is a mechanism for encapsulating a content client side that is not rendered when the page is loaded, but can be instantiated later at execution time using Javascript.

Think of the template as a piece of content, which is stored for possible future use in the document. While the parser processes the element content when loading the page, that’s just ensures that the content is valid; however, the content of the element still was not rendered.

Making the document body more readable and easier to maintain in the template.

function addAgregado() {  
  $("#riscos").append($("#riscoform").html()).on('click','.remover_campo', function(e){
    $(event.target).parents('table').remove();
  });  
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">      
    <title>Riscoform</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <template id="riscoform">
       <div>
         <table class="campo" cellspacing="10">
            <tr class="elimininput">
              <td style="display: none;">
                <div class="hs_firstname field hs-form-field">
                  <label>Id<input name="IdAgreg[]" type="text"></label>
                </div>
              </td>
              <td>
                <div class="hs_firstname field hs-form-field">
                  <label>Parentesco
                    <input name="Parent[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório">
                       <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                       </span>
                  </label>
                </div>
              </td>
              <td>
                <div class="hs_firstname field hs-form-field">
                  <label for="ParentNome">Nome
                    <input name="ParentNome[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório">
                    <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                    </span>
                  </label>
                </div>
             </td>
             <td>
               <div class="hs_firstname field hs-form-field">
                 <label for="ParentIdade">Idade
                   <input name="ParentIdade[]" required="required" type="text" placeholder="" data-rule-required="true" data-msg-required="Campo obrigatório">
                   <span class="error1" style="display: none;">
                        <i class="error-log fa fa-exclamation-triangle"></i>
                   </span>
                 </label>
               </div>
             </td>
             <td><button class="remover_campo"><i class="fa fa-trash"></i></button></td>
           </tr>
         </table>
       </div>    
     </template>
</head>

<body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="hs_firstname field hs-form-field">
        <label for="educacao">Composição do Agregado Familiar (Parentesco, Nome e Idade) <span style="color: red;">*</span></label>
        <button type="button" class="hs-button primary large" onclick="addAgregado()">Adicionar Familiar</button>
   </div>
   <div class="hs_firstname field hs-form-field" id="riscos"></div>
</body>
</html>

Browser other questions tagged

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