CaptainObvious
CaptainObvious

Reputation: 79

Javascript prompt alternative in Loop

So, instead of a prompt, I could use an <input type="text"> and a button to do stuff with the values of the input on button click, for example:

var x = [];

$('button').on('click', function(){
  x.push($(input[type="text"]).val());  
});

However, in a loop for example:

var y=0;
var z=[];
do {
  z.push(prompt('input value'));
  y++;
}
while (y<5);

The loop would prompt for a value, user inputs value, prompt assigns value to array, then the loop would prompt again until y reaches 5.

Instead of a prompt, I'd like to do this with my text field input and button. How can I get the loop to pause, wait for user to input text, and submit by clicking button, every time it reaches that part of the loop?

Edit: The pushing of 5 values into the array was just an example. Let's say I wanted to create a game where the loop would move up with an "up" and down with a "down" input. I want to be able to request user input during the loop, similar to how the prompt would do it, but without using prompts.

Upvotes: 4

Views: 439

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

You don't. You completely change your logic, losing the loop entirely:

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've edited the question and commented below that what you do next might vary depending on the input. That's not a problem, you just apply the event-response model to your new requirement. For instance, you said

...Let's say I wanted to create a game where the loop would move up with an "up" and down with a "down" input.

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 you might handle dispatching, not necessarily a switch. For instance:

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();
    }
});

And so on. The key is that instead of working iteratively (I do this, I get that input, I do the next thing, I get more input), you're working reactively: I get input, I do something. That might require some kind of state management (remembering where you are) beyond what's shown above (the first example has state management: We check the length of z to see how many inputs we've collected).

Upvotes: 8

Related Questions