Javascript Prompt inside loop - Stack Overflow

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

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

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

Share Improve this question asked Apr 15, 2013 at 10:40 user2181271user2181271 31 silver badge3 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 3

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

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745212928a4616949.html

相关推荐

  • Javascript Prompt inside loop - Stack Overflow

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

    4小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信