user2181271
user2181271

Reputation: 3

Javascript Prompt inside loop

for (var j=0; j<2; j++){
listno=prompt("Enter Item Code","0");
listno = parseInt(listno);

if (listno > 0) {
    PRODUCT_WANT.push(PRODUCT_LIST[listno]);
    WANT_PRICE.push(PRICE_LIST[listno]);
}

else {
alert('Invalid Product Code');
}
if (quantno > 0) {
    quantno=prompt("Enter Quantity","0");
    quantno = parseInt(quantno);
    quantity.push(quantno);
}

else {
alert('Invalid Quantity');
}
}    

The loop works but I don't want to have to set the loop count I want to be able to put it to eg 999 then be able to press cancel on the prompt and have the loop finish

Upvotes: 0

Views: 9393

Answers (2)

ArchiFloyd
ArchiFloyd

Reputation: 1294

What you want is a while loop :)

As an elaboration to Davids answer: What a while loop is doing is that the "body" of the while loop is executed, until a condition is meet. So first of, you want to have some condition that can evaluate to either true or false. If the condition is true, the "body" of the while loop is executed, and in the "body" you can change the condition. Giving an example

var i = 0;
while(i < 20)
{
    i = i+1;
}

the above will run as long as i is smaller than 20.

Upvotes: 0

David Hedlund
David Hedlund

Reputation: 129792

prompt will yield null if cancel is pressed.

You might do something like this:

while(listno = prompt("Enter Item Code", "0")) {
   ...
}

Edit. The result of prompt will be whatever was written in the input prompt, or null if cancel was pressed. Since null will evaluate to false when used in a condition, you can use it in a while loop, to run some code while the prompt evaluates to true, i.e. keep prompting as long as a valid number is entered.

Demo

Upvotes: 3

Related Questions