When the button is pressed, only the handler function works, the code which is written after - worked after the handler was created.
a does not exist before pressing the button. Initially, an alert is displayed, and then we press any button in #search and alert with the output of a already swallowing flash
$('#search').on('keyup', function() { a = 'test'; console.log(a); // test }); console.log(a); // a is not defined
$('#search').on('keyup', function() { a = this.value; f(a); }); function f(a) { console.log(a); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input id='search'>
You can declare a variable before the handler, assign a value to it in the handler, and then use it anywhere
a = null; $('#search').on('keyup', function() { a = this.value; }); $('button').click(function() { console.log(a); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> <input id='search'> <button>получить значение</button>