Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading