I want to create a JavaScript function that will create an HTML form and return the input that the user enters into the form. My stupid first attempt was something like this:
function getInput() { $('#somediv').html( "<input type='button' id='mybutton' name='Click Me'></input>" ); $('#mybutton').click( function() { return "result"; } ); } result = getInput(); alert( result );
(The actual situation is more complicated, the user must first enter the text, and then choose between several different buttons, and the return value depends on the entered text and the selected button, but I think these are peripheral problems, so I left them). If I run it as written, I will get a warning “undefined”, where what I want is the “result”. Essentially, I want the function not to return until it explicitly tells it to do so. Is there any way to achieve this? If not, what is the simplest workaround similar in spirit to the above?
A very similar question was asked here: JavaScript pauses the function to wait for user input . I'm afraid I just could not understand the answers well enough to adapt them to my specific case. Perhaps someone can advise how to do this, or, alternatively, starting from scratch will also be good.
source share