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

153
Vistas
Run function only once for particular element

I am building a simple todo app and I am new in JavaScript and I am stuck in a problem.

I am trying to run function only once for a particular element ID. like,

There are 5 divs with IDs 1,2,3,4,5. so I am accessing them by className and then their ID.

Then I am storing their id in a variable and storing it to prevent the function from running with the previous id.

page.html

function myFunction() {

    // Used for getting last element of all the classes
    var element = Array.from(document.querySelectorAll(".fields")).pop();

    var previousId = element.id;

    var executed = false
    if (previousId === element.id) {
         if (!executed) {
            executed = true;
            console.log("Run only once");
            console.log(previousId);
        }
    }
}
<input type="text" id="1" oninput="myFunction(id)" class="fields">

<input type="text" id="2" class="fields">

What I am trying to do ?

I am trying to run the function only once for the current input field user is typing in.

I tried removing if (previousId === element.id) { and running only if(!executed){ but it also didn't worked.

But Whenever I type in input field then it executing every time I press the key.

I have tried many times but it is still not working. Any help would be much Appreciated. Thank You in Advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can save an array of already runned id and chek it

let alreadyRunned = []

function myFunction(id) {
  if (alreadyRunned.includes(id)) {
    return;
  }
  alreadyRunned = [...alreadyRunned, id]
  console.log("Run only once");
  console.log(id);
}
<input type="text" id="1" oninput="myFunction(1)" class="fields">

<input type="text" id="2" class="fields" oninput="myFunction(2)">

about 4 years ago · Juan Pablo Isaza Denunciar
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