0

I need to call a function in a loop.

I have the following code....

do {
    var name = prompt("Enter name:");

    if (!isNaN(age) && name != null && name != "") {
        names[i] = name;
    }
    loop = confirm("Add new name?");

    i++;
    // at this place I want to call the function
    // addnew(document.getElementById("newtable")"; so when someone clicks cancel in the confirm box the javascript creates a dynamic table from the array names
} while (loop);​

Anyone knows how I can call the function addnew?

ultranaut
  • 2,132
  • 1
  • 17
  • 22
  • 1
    What is the problem? Just remove your comment so `addnew()` runs? – Brad Oct 13 '12 at 21:40
  • 2
    Are you really asking how to call the function addnew - or how to implement the function addnew? You would call the function addnew in exactly the same way you called the other functions in your code example. – James Gaunt Oct 13 '12 at 21:41
  • Calling it after the loop should work. – pimvdb Oct 13 '12 at 21:41
  • I'm pretty sure that "loop" is all kinds of messed up, beginning with `age` not being defined, so it's throwing a `ReferenceError` right off the bat. – ultranaut Oct 13 '12 at 21:51

2 Answers2

0

I'm guessing that you want the function called when the Confirm answers yes and terminate the loop when it doesn't which could be implemented like this:

while(true) {
    var name = prompt("Enter name:");
    if (!name) {
        break;
    }

    if (!isNaN(age)) {
        names[i] = name;

    }


    if (!confirm("Add new name?")) {
        break;
    }

    i++;
    // at this place I want to call the function
    addnew(document.getElementById("newtable")); 
}
jfriend00
  • 683,504
  • 96
  • 985
  • 979
0

Are you looking to do something like this:

var name,
names = [];

function coolFunc(names) {
    console.log(names);
}

do {
    var name = prompt("Enter name:");

    if (name != null && name != "") {
        names.push(name);
    }
    loop = confirm("Add new name?");

//  if you want to handle the names one-by-one as you get them, then you could call 
//  your function here, otherwise call it when you exit the loop as below

} while (loop);

coolFunc(names);

I removed the test for age because there isn't anything in what you posted to indicate where that's coming from and so was throwing an error, so you'd need to work that back in as appropriate, and i didn't really seem necessary but was also throwing an error.

ultranaut
  • 2,132
  • 1
  • 17
  • 22