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


i want able click submit button after inputting text forms, click results button display input.

it seems titles variable "stuck" in function onclick(event) function. how "get 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 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 been answered don't know enough jargon search answer. used of code here cause want take in 2 string inputs: get values multiple inputs jquery

first of all, have typo in selector second click event. should #results, rather #result

to core of problem, titles variable out of scope in second click event.

you can remedy declaring outside of either function. let reference in either one.

var titles = [];  function onclick(event) {   titles = $('input[name^=titles]').map(function(idx, elem) {     return $(elem).val();   }).get();   window.alert(titles); }  $("#results").click(function() {   window.alert(titles);   $("p").text(titles[0]); }); 

Comments