Alternative Javascript in Loop
So, instead of being prompted, I could use <input type="text">
and button
to do things with the input values ββwhen the button is clicked, like this:
var x = [];
$('button').on('click', function(){
x.push($(input[type="text"]).val());
});
However, in a loop like:
var y=0;
var z=[];
do {
z.push(prompt('input value'));
y++;
}
while (y<5);
The loop will ask for a value, enter a user value, prompt to assign a value to an array, then the loop will ask again until y reaches 5.
Instead of being prompted, I would like to do it with a textbox input and a button. How can I get the loop to stop, wait for the user to input text, and submit on a button click every time it reaches that part of the loop?
Edit: pushing 5 values ββinto an array was just an example. Let's say I wanted to create a game in which a loop would move up with up and down with down. I want to be able to prompt for user input during a loop, similar to how a prompt would do, but without prompts.
Not. You completely change your logic, completely losing the loop:
var z = [];
$('button').on('click', function() {
z.push($(input[type="text"]).val());
if (z.length === 5) {
// Do what you would have done after the end of the loop here
}
});
You edited the question and commented below that what you do next may vary based on input. This is not a problem, you just apply the event-response model to your new requirement. For example, you said
... Let's say I wanted to create a game in which the loop would move up with up and down with down.
Then:
$('button').on('click', function() {
switch ($(input[type="text"]).val().toLowerCase()) {
case "up":
// Do the "up" thing
break;
case "down":
// Do the "down" thing
break;
}
});
There are several different ways to handle dispatching, not necessarily switch
. For example:
var actions = {
up: function() {
// Do the "up" thing
},
down: function() {
// Do the "down" thing
}
};
$('button').on('click', function() {
var action = actions[$(input[type="text"]).val().toLowerCase();
if (action) {
action();
}
});
Etc. The key is that instead of working iteratively (I do this, I get this input, I do the following, I get more input), you work reactively: I get the input, I do something. This may require some kind of state management (remember where you are) above what is shown above (the first example has state management: we check the length z
to see how many inputs we collected).