3

I'm working on a text-based browser game made using Javascript and JQuery. I've run into a problem with user input. What I used to do was just use a prompt() because it was easy to use, allowed me to save the input to a variable and made the code wait for input.

Now I want it to look better, so I've made my own input field with a nice chatbox above it. What I wanted to know was how to stop the code from executing untill the user has pressed enter (I already detect the enter press and the text is being appended to the dialog box, I just need the code to wait for that to happen before it continues).

Here's some of my code:

Function for input

function input_field() {
    var inputField = $('#dialog-input');
    var messageField = $('#dialog-text');

    inputField.keyup(function (e) {
        if (e.keyCode == 13) {
            window.userInput = inputField.val();
            if(userInput != '') {
                messageField.append('You: ' + window.userInput + '<br>');
                inputField.val('');
                messageField.scrollTop(999999999);
            }
        }
    });
}

What I'd like to do is just save the data to a variable and then check it with a switch-case just like with prompt(), but as it stands now it just gives me an error because it tries to execute all the code instead of wait untill the user has given input.

4
  • can you provide a jsFiddle ? Commented Mar 16, 2014 at 1:54
  • @KopaxJackHerrauer Nope :/, too much other code that this relies on, but the issue is not related to that. I just need a way to wait for user input in javascript. Commented Mar 16, 2014 at 1:57
  • I am writing a simple example wait a minute Commented Mar 16, 2014 at 1:57
  • You can't "wait for user input" before continuing to execute javascript without using one of the built-in functions like prompt() or alert(). Javascript simply doesn't work that way. The usual way to solve this is to disable the rest of the UI on the page, put up your dialog and then respond to an event for OK or Cancel and based on one of those events call the rest of your code. Commented Mar 16, 2014 at 2:27

2 Answers 2

4

It is possible with async+await.

Please note, that it is currently not fully supported by all browsers (http://caniuse.com/#search=await) and that there are probably better solutions to this kind of problems.

Using await myAsyncFunction() makes the browser treat the function like it is synchrounous, therefore it stops further execution of this function until a result is returned by the awaited function. It does not block other code on the website from running.

await may only be used inside a async function, otherwise the browser will throw an error.

Here is an example showing how you could wait for user input with await+async:

async function handleForm() {
  let userInput = '';
  console.log('Before getting the user input: ', userInput);
  userInput = await getUserInput();
  console.log('After getting user input: ', userInput);
};

function getUserInput() {
  return new Promise((resolve, reject) => {
    $('#myInput').keydown(function(e) {
      if (e.keyCode == 13) {
        const inputVal = $(this).val();
        resolve(inputVal);
      }
    });
  });
};

handleForm();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput">

Sign up to request clarification or add additional context in comments.

2 Comments

why did you write const test = await 20; ? can 20 be any other number?
@Yolomep I have no idea why I did that initially, probably trying out if it works. It is definitely not necessary and has no benefits, so I just removed this line from the code snippet.
-3

You have to thing differently, while javascript stop and wait for a returned value when using prompt(), you can't directly achieve that with a custom prompt.

var result = [];
for(var i = 0; i > 5; i--){
    result.push( prompt('tip something') ); // Ok
};

javascript will break until prompt return something

but you can't tell your code to stop, like the browser does when promprting. You'll have to execute a code when closing the modal (on button click or keypress enter) that open/update the next modal.

5 Comments

I don't get what this code is supposed to do. It still uses a prompt?
it's a custom prompt, try it in a html page. I am updating my answer
Ok, but I don't want a custom prompt. I have an input field and dialog box and I need some function to ask the user a question, wait for the users response and then proceed with the code as normally. This custom prompt doesn't wait for the input like a normal prompt.
i'm giving you an answer, you can't achieve that like browser does, I gave you a custom prompt. see @jfriend00 response , you can't stop a script without telling him to stop, opening the prompt must stop the script, and closing it start it again, if you need more explanation, ask for it
I didn't vote you down, but thanks for being so "nice". Your custom prompt is nothing like what I asked help for btw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.