jquery – How to dynamically add input after second table header

Question:

I have a problem, I would like to dynamically insert inputs into a table with more than one header, in my script when I click on the + image, the lines are being added after the first header but not in sequence, that is, in the lines following the second header, as well as deleting the lines of the first header and also the second.

I put an example in JSFiddle, see:

https://jsfiddle.net/t5soaubu/

I tried to make a change to this code snippet inserting the class linhas , but without success:

    <tr class="linhas">
  <td><input type="text" name="rg[]" style="text-align:center" id="rg[]" /></td>
  <td><input type="text" name="endereco[]" style="text-align:center" id="endereco[]" /></td>
  <td><input type="text" name="municipio[]" style="text-align:center" id="municipio[]" /></td>
  <td><input type="text" name="uf[]" style="text-align:center" id="uf[]" /></td>
</tr>

Answer:

You can target the second header by putting a specific class:

HTML

<tr class="segundoHeader"> ... </tr>

Javascript

$(".adicionarCampo").click(function () {
    novoCampo = $("tr.linhas:first").clone();
    novoCampo.find("input").val("");
    novoCampo.insertAfter("tr.linhas:last");

    novoCampo = $("tr.segundoHeader:first").clone();
    novoCampo.find("input").val("");
    novoCampo.insertAfter("tr.segundoHeader:last");  

    removeCampo();
});

JSFiddle: https://jsfiddle.net/t5soaubu/4/

Scroll to Top