How do i get the variable from a keydown event to use it globally

I have a global variable called newSearch after clicking enter i want to use the stored variables received from the input to concatenate in my ajax URL request. However i get undefined because the variable doesn’t change globally and only works inside the keydown event function.What am i doing wrong?

$("#searchBar").on("keydown",function search(e) {
         var newSearch;
        if(e.keyCode == 13) { 
           newSearch = $('#searchBar').val();
        //Requesting data from api

Don’t use global variables. Everything you want to do should be done inside that event handler. When you rely on global variables, you quickly run into race conditions and scoping issues.

1 Like

While I agree with Portable’s advice, I’m looking at your code.

Do I understand that you have newSearch declared outside this event handler (to make it global also? If you’ve already declared newSearch outside of the event handler and then redeclare it (as you seem to do on the first like of your event handler) then you now have two instances with the same name and you get into some complicated scoping issues. Inside the event handler, the local variable would be accessed as newSearch but to access the global one, it would have to be something like window.newSearch to make it clear. But if a global variable is already declared, then don’t redeclare it.

If you really, really wanted to do it, then I’d remove the newSearch declaration in the event handler (assuming that my inference is correct, that it’s declared somewhere else globally).

But Portable is right - you have to be careful with global variables, especially when dealing with asynchronous functions You should probably rethink how your doing your algorithm and try to put it in the event handler, even if you have to call other functions from the event handler.

1 Like
         if(e.keyCode == 13) { 
                dataFromApi();   // call a function you create
//The function you create eg
function dataFromApi(){
var newSearch = $('#searchBar').val(); // create variable here ....
// rest of your code .......

this is how i did something similar with my wikipedia code ... eg someone enters something in the search then hits enter .... i check if keycode is enter like you do .... **then i call a function** .... in the function i assign  whatever is in the search to the variable and then i add this to my  var for the url and then send off a ajax request to the api.
no global variable needed .... think this should sort your problem
1 Like

Thanks alot guys the structure of coding is really getting the best of me. @JohnL3 thats a great solution i’m gonna give it a try now, because this was happening i wrote my entire ajax request in the if statement xD