Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!