• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

117
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 3 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 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda