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

308
Visualizações
How to stop script when I am done for the first time, JavaScript

everyone! I have been working on a project in JavaScript, usually sending requests to the server using ajax. I want to display a confirmation message and allow the user to press the continue button to continue with the request. When I execute the first click which displays the confirmation dialog, the script runs correctly once. However, when I try clicking on the button again, the script executes twice and keeps incrementing the number of times I click the submit button, it only runs correctly when I refresh the page. Actually, the first click is on a click function that I call on every different result returned from the PHP script and I need the id to send a request against it. I am looking for a way in which I will be able to clear the script execution and let it start over each time I click the submit button. Here is the sample:

 ...
   function removePerson(id) {
       $("#confirmDialog").show(function(){
           $("#confirm").click(function(){
               $.post('server/process.php'{id:id});
       });
   }

Please, I really need your help with this.

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

0

The problem is that you are attaching a new event handler to the confirm button on each call to removePerson. You can use .off("click") to remove the previous event handler before registering a new one. Something like this should work:

function removePerson(id) {
  $("#confirmDialog").show();
  $("#confirm").off("click").on("click", function() {
    $.post("server/process.php", { id: id });
    
    // just for the demo
    console.log(id);
    $("#confirmDialog").hide();
  });
}
#confirmDialog {
  display: none;
  padding: 20px;
  background: #eee;
  margin-bottom: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="confirmDialog">
  Remove person? <button id="confirm">confirm</button>
</div>

<button onclick="removePerson(1)">remove ID 1</button>
<button onclick="removePerson(2)">remove ID 2</button>
<button onclick="removePerson(3)">remove ID 3</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