JavaScript function that creates an HTML form and returns user input

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.

+4
source share
2 answers

It is impossible to wait for user input in this form. You need to split it into two parts to handle the asynchronous request.

 function getInput(callback) { $('#somediv').html( "<input type='button' id='mybutton' name='Click Me'></input>" ); $('#mybutton').click( function() { callback("result"); } ); } function processInput (result) { alert(result); } getInput(processInput); 
+2
source

I think you are looking for event delegation, using delegation delegation, you can bind your function to your #mybutton before your button is added to your form.

For example, using . on ()

  $(document).on('click', '#mybutton', function() { //your code here }); 

The basic idea of ​​event delegation is to take advantage of the fact that bubbles appear in JavaScript events, so what you do is associate the event with a higher element in the DOM , and then check where it comes from while there is a higher level in The event binding time is OK.

+1
source

Source: https://habr.com/ru/post/1443566/


All Articles