Count fields as they are included with Jquery

Asked

Viewed 49 times

0

I have the form below which when I click Add more Pets, it includes perfectly. So far it is working 100%, see:

inserir a descrição da imagem aqui

Notice that I have a numbering next to the title #1. I would like as new ones are included panels, were being numbered: #1, #2, #3, #N...

I tried it this way:

HTML

<div class="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");
       }
    });

However it numbers only in the first panel, see below when I include another field, ie total of 02 fields:

inserir a descrição da imagem aqui

1 answer

2


Exchange 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 made some small modifications to your code, for example, declared the variables. This is an important practice in Javascript.

Always preceded by a variable by var in your statement. For example, var i = 1;.

Browser other questions tagged

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