How to wait for an event before returning a value js

52 views Asked by At

I am making a custom prompt that I can get the return value by doing var = customPrompt() and I came into a problem returning the value as I did it like this, and it didnt ever return the value. I also came across using await, but I was wondering if there was a simpler method I maybe missed?

submitButton.onclick = function () {
  var userInput = document.getElementById("userInput").value;
  closePrompt();
  return userInput;
};
1

There are 1 answers

8
Vladislav Utkin On

As Rory McCrossan said in comments, you can't return something from event handler because it is just invoked then doing something and that's it. If you want to get an input value you should make variable in closure higher where you will be able to take it and use.

let inputValue;

submitButton.addEventListener('click', function () {
  let input = document.getElementById("userInput");
  if(input) inputValue = input.value;
  closePrompt();
});

Of course you will receive the value only when you click on the button. Before this it will equal undefined.

If i got it wrong please describe your case clearlier and give more code examples your case connected with.