Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
Event handler invoked twice for a single click event

I'm mimicking a stack overflow question detail page where a user has the ability to delete their own answer to a particular question. The page has an element representing the total count of answers posted (0 answers, 1 answer, 2 answers, etc...). Once a User clicks on <p class="delete_answer">delete</p>, an AJAX request is sent to the API, the model is deleted, and the API returns a 204 status code Response.

The desired outcome after the receiving the response is to decrement the answer count by 1 point. Yet the actual outcome decrements the answer counter by 2 points. If there is 1 answer and it's deleted, it will go from 1 answer to -1 answer yet it's suppose to be 0 answers.

It appears then that event handler is being invoked twice. What is causing this to occur and how can it be remedied so the count decrements by 1?

  let posted_question_answers = document.querySelectorAll(".delete_answer");
  posted_question_answers.forEach((answer) => {
    answer.addEventListener("click", function(event) {
      const question_answer = this.id;
      console.log(question_answer);
      let [question_id, answer_id] = Array.from(question_answer.matchAll(/(?<=\w+)\d+/g));
      console.log(question_id, answer_id);
      var answer_vote = question_answer.split("__")[1];
      const [answer, vote] = answer_vote.split("_")

      const request = new Request(
        `http://localhost:8000/api/v1/questions/${question_id}/answers/${answer_id}/`, {
          'method': 'delete',
          'headers': headers
        }
      );
      fetch(request).then((response) => {
        this.parentElement.parentElement.parentElement.parentElement.remove();
        let answer_count = document.getElementById("answer_count");
        const n = parseInt(answer_count.textContent[0]) - 1;
        console.log(n)
        let answers;
        if (n > 1 || n == 0) {
          answers =  ` answers`;
        } else {
          answers = ` answer`;
        }
        answer_count.textContent = `${n} ${answers}`
      })
    })
  })
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda