Post fields as they are included with Jquery

0

I have the form below which when I click on Add More Pets , it includes perfectly. So far it's working 100%, see:

PleasenotethatIhaveanumberingnexttothetitle#1.Iwouldlikeasnewpanelstobeincluded,benumbered:#1,#2,#3,#N...

Itriedthefollowing:

HTML

<divclass="panel-heading">
<span id="contar">#1</span>  <i class="fa fa-paw fa-lg" aria-hidden="true"></i> DADOS DO PET
</div>

JQUERY

$(".adicionarCampo").click(function() {
      novoCampo = $("tr.linhas:first").clone();
      novoCampo.find('input[type="text"]').val("");
      novoCampo.find('select').val("");      
        if ($("tr.linhas").length < 20) {
            for(i = 0; i < $("tr.linhas").length; i++){
                contar = i + 2;
                $("#contar").append(contar);
            }
          novoCampo.insertAfter("tr.linhas:last");
       }
    });

But it numbers only in the first panel, see below when I include one more field, that is, total of 02 fields:

    
asked by anonymous 26.08.2017 / 19:32

1 answer

2

Change JavaScript for this:

/*globals jQuery*/
(function($) {
  $(".adicionarCampo").on('click', function() {

    var novoCampo = $("tr.linhas:first").clone();

    novoCampo.find('input[type="text"]').val("");
    novoCampo.find('select').val("");

    var number = parseInt(novoCampo.find('#contar').text().replace('#', ''));
    novoCampo.find("#contar").html('#' + parseInt(number + 1));

    if ($("tr.linhas").length < 20) {      
      novoCampo.insertAfter("tr.linhas:last");
    }
  });
}(jQuery));

If you notice, I've made some minor modifications to your code, for example, I declared the variables . This is an important JavaScript practice.

Always precede a variable with var in your declaration. For example, var i = 1; .

    
27.08.2017 / 21:18