'How do I display a jquery variable obtained from user input?

I want to be able to click the submit button after inputting some text into the forms, then click the results button to display what I just input.

It seems like the titles variable is "stuck" in the function onClick(event) function. How do I "get it out?"

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<body>
<script type="text/javascript">
    $(document).ready(function() {
        $(function() {
            $('#submit').click(onClick);
        });

        function onClick(event) {
            var titles = $('input[name^=titles]').map(function(idx, elem) {
                return $(elem).val();
            }).get();
            window.alert(titles); //it displays the titles here
        }

        $("#result").click(function() {
            window.alert('x');
            window.alert(titles); //but not here
            $("p").text(titles[0]);
        });
    });
</script>
    <p>display results here</p>
    <input name="titles[]">
    <input name="titles[]">
    ​<button id="submit">submit</button>
    <button id="results">results</button>
</body>

This has probably been answered already but I don't know enough jargon to effectively search for an answer. Also I used some of the code from here cause I want to take in two string inputs: Get values from multiple inputs jQuery



Solution 1:[1]

Hi Austin when you click on submit jquery calls your function onClick but this function has nothing to do with the one that you register here

$("#result").click(function() { // resultCallback

so when you define the variable

var titles

this variable, like you say, is bound (scoped) to the function onClick and you can't access it from resultCallback. Plus it is completely asynchronous. Clicking on result button (ie calling resultCallback) is not clicking on submit button (ie calling onClick) and because of this the variable titles won't be loaded.

If you want to retrieve the titles create a function getTitles that internally contains

return $('input[name^=titles]').map(function(idx, elem) {
    return $(elem).val();
  }).get();

and call it from your functions.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hdcos