Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

135
Visualizações
How to limit jQuery appending to form

I have added this link for adding new row to my form:

<a id="add" class="btn btn-info" style="color:white">New row</a>

And here is the jQuery code:

$(document).ready(function(){
            var i = 1;
            if(i == 1){
                $('#add').click(function(){
                    i++;
                    $('#dynamic_field').append("HERE GOES THE ROW ELEMENTS");
                });
            }
        });

And it works fine.

But I need to determine that add new row only one time and not several times.

So I tried checking if(i == 1){ in the jQuery, but does not seem to be working and user still can adds new row multiple times.

So how can I limit this to only one time?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

you need to use one with click event:

$(document).ready(function(){
 $('#add').one('click', function(){
    $('#dynamic_field').append("HERE GOES THE ROW ELEMENTS");
  });
});

This will invoke click event only once.

about 4 years ago · Juan Pablo Isaza Relatório

0

Kiran 's answer, which is the better approach in my opinion, but I tried to extend your code with n times.

const unbindEventWithParam = (n, fn) => {
  let i = 0
  function addRow(event){
    console.log('event is running')
    i++
    fn()
    if(i == n) return $(this).off(event.type)
  }
  return addRow
}
const addRow = unbindEventWithParam(2, function(){
  $('#dynamic_field').append("add row 1 ")
})
const addRow1 = unbindEventWithParam(4, function(){
  $('#dynamic_field1').append("add row 2 ")
})
$('#add').click(addRow)
$('#add1').click(addRow1)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="add" class="btn btn-info">New row</a>
<div id="dynamic_field"></div>
<a id="add1" class="btn btn-info">New row1</a>
<div id="dynamic_field1"></div>
<button id="new-event">New event</button>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda